2012-11-04 61 views
0

我不明白這個錯誤。如何讓「內容」變得可寫?BeautifulSoup類型錯誤

from bs4 import BeautifulSoup 

soup = BeautifulSoup(open("http://www.asdf.fi/asdf.html")) 

content = soup.find(id="content") 

with open("test.html", "a") as myfile: 
    myfile.write(content) 

錯誤:

Traceback (most recent call last): 
    File "<stdin>", line 2, in <module> 
TypeError: expected a character buffer object 

回答

1

首先,你不能打開使用open()網頁。您需要使用urllib庫(實際上我使用mechanize庫,它更易於使用)。

二,open()返回一個file對象,不能傳遞給BeautifulSoup()。你需要寫類似

soup = BeautifulSoup(open(filename).read()) 

.read()讀取整個文件,並返回字符緩衝區,可用於調用BeautifulSoup()

+0

啊,好的謝謝。 BTW ... soup = BeautifulSoup(open(filename.read())) – Leke

+0

不能,'.read()'不是'str'類的方法,它是'file'類的一個方法。 – 0605002

0

好了,經過一番搜索...

with open("test.html", "a") as myfile: 
    myfile.write(content.encode('utf-8'))