2016-09-28 129 views
-1
from bs4 import BeautifulSoup 
import requests 
import csv 


page=requests.get("http://www.gigantti.fi/catalog/tietokoneet/fi_kannettavat/kannettavat-tietokoneet") 

data=BeautifulSoup(page.content) 

h=open("test.csv","wb+") 
h.write(data) 
h.close() 

print (data) 

我已經嘗試運行的代碼,因爲它是沒有csv文件打印出來,並將其完美地運行,但現在我嘗試將它保存爲CSV我得到錯誤:參數1必須可以轉換爲緩衝區,而不是BeautifulSoup。請幫助,並提前致謝類型錯誤:參數1必須轉換到一個緩衝,而不是BeautifulSoup

+0

查看鏈接後,我只能假設您試圖刮取產品信息。如果這就是你想要的,那麼你在你的代碼片段中所做的沒有意義,因爲你只是將整個頁面保存爲一個字符串(這太錯誤了!)。有關如何使用標識符查找某些元素的詳細信息,請參閱[bs4docs](https://www.crummy.com/software/BeautifulSoup/bs4/doc/)。 – r3ign

+0

@ r3ign先生我的道歉,如果我無法解釋清楚。 Sir Im試圖從網站上刮掉這些網址,但是如果我沒有將它們轉換成字符串,它們會將它們保存在csv文件中,它會顯示格式錯誤。但是我肯定會按照你的建議引用bs4docs。謝謝 –

+0

如果您需要完整的視頻教程,請按照[此視頻](https://www.youtube.com/watch?v=3xQTJi2tqgk)從頭開始學習。 – r3ign

回答

1

你正在嘗試做沒有任何意義。作爲Beautiful Soup Documentation提到

Beautiful Soup is a Python library for pulling data out of HTML and XML files. It works with your favorite parser to provide idiomatic ways of navigating, searching, and modifying the parse tree. It commonly saves programmers hours or days of work.

你似乎並不被拉動的任何數據,但你試圖寫一個BeautifulSoup對象到文件,該文件是沒有意義的。

​​

什麼,你應該使用BeautifulSoup的是搜索數據的一些信息,然後利用這些信息,下面是一個無用的例子:

from bs4 import BeautifulSoup 
import requests 
page = requests.get("http://www.gigantti.fi/catalog/tietokoneet/fi_kannettavat/kannettavat-tietokoneet") 

data = BeautifulSoup(page.content) 
with open("test.txt", "wb+") as f: 
    # find the first `<title>` tag and retrieve its value 
    value = data.findAll('title')[0].text 
    f.write(value) 

好像你應該使用BeautifulSoup到如果我正確猜測,請將產品列表中每個產品的所有信息都收回並放入csv文件的列中,但我將把這些工作留給您。您必須使用BeautifulSoup找到html中的每個產品,然後檢索其所有詳細信息並打印到csv

2

我不知道是否有人能夠解決它,但我的命中和審判工作。問題是我沒有將內容轉換爲字符串。

#what i needed to add was: 
#after line data=BeautifulSoup(page.content) 
a=str(data) 

希望這有助於

相關問題