【问题标题】:AttributeError: 'NoneType' object has no attribute 'replace_with'AttributeError:“NoneType”对象没有属性“replace_with”
【发布时间】:2014-09-08 10:13:44
【问题描述】:

我收到以下错误:

Traceback (most recent call last):
  File "2.py", line 22, in <module>
    i.string.replace_with(i.string.replace(u'\xa0', '-'))
AttributeError: 'NoneType' object has no attribute 'replace_with'

部分代码

soup = bs4(open("test.html")) 

table = soup.find("table", {"color":"#fff"})

for i in soup.find_all('small'):
    i.string.replace_with(i.string.replace(u'\xa0', '-'))  <--Line 22

昨天它还在工作,但我不得不在另一个 VM 上重新安装 Mint,但我无法让它再次工作。我该如何解决?

编辑:这是所有代码:

from bs4 import BeautifulSoup as bs4

soup = bs4(open("test.html")) 

table = soup.find("table", {"color":"#fff"})

for i in soup.find_all('small'):
    i.string.replace_with(i.string.replace(u'\xa0', '-'))

#print soup
f = open("new.html", "w")
f.write(str(table))

这是 test.html 中的表格:

<table color="#fff">
<tr>
<td><small><small>&nbsp;</small></small></td>
</tr>

</table>

【问题讨论】:

  • 发布更多代码。 i 是什么?
  • @stalk 添加了一些代码。我正在阅读一个 html 文件
  • replace_with() 还是replace_width()?你在你的问题中都使用了。会不会是您的代码中的拼写错误?
  • @FrédéricHamidi 抱歉,我打错了。它是 replace_with
  • 显然i.stringNone。为什么你认为i.string 不应该是None?你明白错误信息了吗?

标签: python python-2.7


【解决方案1】:

根据documentation.string 属性可以返回None,如果标签“包含多个事物”

这仅表示您列出的元素之一 (soup.find_all('small')) 是非叶元素。例如:

<small>Hello <em>Bobby</em></small>

对于这样的元素,.string 返回 None,因为它包含另一个元素,并且行为未定义。

您的代码不起作用,因为您无法运行None.replace(u'\xa0', '-')。 你需要做的是,在你的循环中,测试被迭代的元素是否有一个定义的.string成员。


for i in soup.find_all('small'):
    if i.string :
        i.string.replace_with(i.string.replace(u'\xa0', '-'))

注意:这是一个肮脏的解决方法,如果你有它就行不通

&lt;small&gt;&amp;nbsp &lt;tag&gt;something unrelated&lt;/tag&gt;&lt;/small&gt;

【讨论】:

  • 我不确定它昨天是否正常工作(以及在那之前的几周),但是当我今天用相同的代码尝试它时,它没有?
  • @tonyt - 可能站点/您的文件的结构发生了一些变化。
  • 在我看来,如果您的脚本工作了一段时间,那么您正在解析的页面一定已经发生了变化,它创建了当前讨论的未定义行为。 在分析某些输入时你不能太小心。
  • @WeaselFox 我的想法完全正确。 OP中提到的&lt;small&gt;&lt;small&gt;&amp;nbsp;&lt;/small&gt;&lt;/small&gt;只能破坏整个事情。
  • 我该如何解决这个问题?我仍然需要将&amp;nbsp; 更改为-。我不太确定。
猜你喜欢
  • 2019-01-01
  • 2021-12-26
  • 2019-07-23
  • 2018-05-13
  • 2020-09-07
  • 2017-05-03
  • 2023-03-16
  • 2018-07-14
  • 2013-06-16
相关资源
最近更新 更多