我正在尝试从 url 中提取数据,但在写入文件时出现此错误,因为 text
不为空。
我的代码:
def gettextonly(self, url):
url = url
html = urllib.urlopen(url).read()
soup = BeautifulSoup(html)
# kill all script and style elements
for script in soup(["script", "style","a","<div id=\"bottom\" >"]):
script.extract() # rip it out
text = soup.findAll(text=True)
#print text
fo = open('foo.txt', 'w')
fo.seek(0, 2)
if text:
line =fo.writelines(text.encode('utf8'))
fo.close()
错误:
in gettextonly
line =fo.writelines(text.encode('utf8'))
AttributeError: 'ResultSet' object has no attribute 'encode'
最佳答案
soup.findAll(text=True)
返回一个 ResultSet
对象,它基本上是一个没有属性 encode
的列表。您要么打算使用 .text
来代替:
text = soup.text
或者,“加入”文本:
text = "".join(soup.findAll(text=True))
关于python - 属性错误: 'ResultSet' object has no attribute 'encode' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35814213/