如何修复错误"NoneType' object has no attribute text"?



这是我的代码的相关部分:

def _get_data(self, html):
doc = html.find('td', {'class': 'White'})
doc_list = html.find_all('p', {'class': 'bib'})
# Принято решение об отказе в регистрации (последнее изменение: 20.08.2020)
text = ' '.join(doc.text.split())[28:]
# ...

整个代码可以在这里找到。

我需要用文档解析一个网站,而网站上有限制。4-5份文件后,你看不到其他文件,你必须等待。所以我做了一个时间限制,但我开始得到奇怪的错误

File "/usr/lib/python3.8/threading.py", line 932, in _bootstrap_inner
self.run()
File "/usr/lib/python3.8/threading.py", line 870, in run
self._target(*self._args, **self._kwargs)
File "/home/yunus/Рабочий стол/RosPatentParser/service/parser.py", line 139, in parse
self._get_data(soup)
File "/home/yunus/Рабочий стол/RosPatentParser/service/parser.py", line 80, in _get_data
text = ' '.join(doc.text.split())[28:]
AttributeError: 'NoneType' object has no attribute 'text' 

我建议在第76行和第77行之间添加以下内容,仅在_get_data函数中添加:

with open('test.html', 'w') as f:
f.write(html)

为了能够对此进行进一步调试。此时,错误告诉您doc是一个NoneType对象(意味着它被设置为None(。通过浏览您的代码,我希望

doc = html.find('td', {'class': 'White'})

以返回CCD_ 4。BeautifulSoup对象在找不到您要搜索的元素时返回None。在这种情况下,您的变量html似乎是一个BeautifulSoup对象,并且它找不到具有类White的td标记。查看html应该会发现你遇到这个问题的原因,并成为解决这个问题的一个很好的起点

最简单的解决方案是简单地检查文本值的存在:

def _get_data(self, html):
doc = html.find('td', {'class': 'White'})
doc_list = html.find_all('p', {'class': 'bib'})
# Принято решение об отказе в регистрации (последнее изменение: 20.08.2020)
if doc.text is not None:  # Only do this if the <td> tag with the class 'White' was found.
text = ' '.join(doc.text.split())[28:]
... # The rest of your code if you find the text
else:
# Handle the case where there are no <td> tags with the class 'White'

如果美丽的汤找不到与之匹配的标签,那么doc.text将是None

相关内容

最新更新