【发布时间】:2020-04-11 15:53:22
【问题描述】:
我正在使用 beautifulsoup(来自 bs4)。我收到TypeError: unsupported operand type(s) for -: 'str' and 'int'。我已经检查了 Stackoverflow 中所有以前的答案,但没有任何效果。
soup = BeautifulSoup(htmltext, 'html5lib')
texts = soup.findAll('p')
visible_texts = filter(visible, texts)
article = ""
for text in visible_texts:
article += text.decode('utf-8')
... other codes
我在article += text.decode('utf-8') 行中收到错误消息。我不明白代码中 int 的位置。变量 article 在循环之前被声明为字符串。 text.decode(...) 以请求的编码返回一个字符串。
filter 参数中可见的是一个自定义函数,而 htmltext 是 request.get() 方法 文本 对象。
任何澄清都会有所帮助。
在文章对象连接之后紧跟在 for 循环之外的下面几行代码。
article = str(article)
article = BeautifulSoup(article, features='html5lib')
print('\n\n\n', article, '\n\n\n')
article = str(article).replace("\n", " ")
【问题讨论】:
-
article的状态是字符串。这就是text.decode('utf-8')我相信text不是string因为str没有方法decode,检查string methods,你在处理Unicode吗? -
@αԋɱҽԃαмєяιcαη .decode() 是 bytes() 类型的方法。请求对象的文本方法以字节格式返回对象。
标签: python-3.x beautifulsoup python-requests