2012-11-04 64 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'))