【问题标题】:Unsupported operand between str and intstr 和 int 之间不支持的操作数
【发布时间】: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", " ")

Full code is available here in case required.

【问题讨论】:

  • article 的状态是字符串。这就是text.decode('utf-8') 我相信text 不是string 因为str 没有方法decode,检查string methods,你在处理Unicode 吗?
  • @αԋɱҽԃαмєяιcαη .decode() 是 bytes() 类型的方法。请求对象的文本方法以字节格式返回对象。

标签: python-3.x beautifulsoup python-requests


【解决方案1】:

您在误导我们,因为您没有包含堆栈跟踪,它讲述的是一个不同的故事。在测试您的代码时,我得到了以下堆栈跟踪:

Traceback (most recent call last):
  File "test.py", line 38, in <module>
    main()
  File "test.py", line 32, in main
    article += text.decode('utf-8')
  File "C:\python-3.7\env\lib\site-packages\bs4\element.py", line 1559, in decode
    indent_space = (' ' * (indent_level - 1))
TypeError: unsupported operand type(s) for -: 'str' and 'int'

因此,引发异常的不是代码中的加法,而是 bs4 代码中的减法。

您收到此异常的原因是您使用不正确的参数调用decode()。定义如下:

decode(indent_level=None, eventual_encoding='utf-8', formatter='minimal')

因此,您代码中的 text.decode('utf-8') 等同于 text.decode(indent_level='utf-8'),这没有意义,因此出现异常。

您可以使用以下任一方法修复错误:

article += text.decode(eventual_encoding='utf-8')

article += text.decode(None, 'utf-8')

PS:下次请在您的问题中包含堆栈跟踪;-)

【讨论】:

    猜你喜欢
    • 2022-07-27
    • 2020-05-19
    • 2021-08-10
    • 2019-11-18
    • 1970-01-01
    • 2016-04-15
    • 2012-11-29
    • 2012-12-31
    相关资源
    最近更新 更多