python - 属性错误: 'ResultSet' object has no attribute 'encode'

标签 python

我正在尝试从 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/

相关文章:

python - 从另一个区域连接到 DocumentDB

python - 值错误 : zero length field name in format with read and write

python - 具有动态 'secondary' 导航栏的 Flask-Nav

python - 在进程池之间共享字典和数组

python - Apache 中的配置错误

python - Python 中的文本冒险问题

python - Django redirect_authenticated_user : True not working

python - 确定 pandas 数据框中的列值何时更改

python - 如何将 pandas.to_datetime 与 "strange"字符串格式一起使用

python - 比较矩阵行与字符串