gpt4 book ai didi

Python - 解决空页面中 Beautifulsoup 的 "object has no attribute"错误

转载 作者:行者123 更新时间:2023-12-01 04:23:41 25 4
gpt4 key购买 nike

为了提取我需要的文本,我可以在条件执行中使用 Beautifulsoup 的 find_next_sibling 抓取大多数网页。

if len(str(h4.find_next_sibling)) < 90:
...
else:
...

但是,对于某个特定页面,该网页是空的,因此 Python 会报告错误:

AttributeError: 'NoneType' object has no attribute 'find_next_sibling'

由于空页面似乎是由我计划抓取的页面列表中的错误产生的,并且我需要 Python 继续抓取而不在每个类似的实例处停止,一种可能性是编写一个 if 条件仅运行当页面中实际存在 find_next_sibling 时上面的代码。有可能做到吗?任何想法表示赞赏!

最佳答案

非常感谢评论者,使用try: except成功解决了这个问题:

try: 
if len(str(h4.find_next_sibling)) < 90:
coverage = h4.find_next_sibling(text=True)
else:
if len(str(h4.find_next_sibling)[1]) < 90:
coverage = h4.find_next_siblings(text=True)[2]
else:
coverage = h4.find_next_siblings(text=True)[1]
except:
coverage = "Empty page"

关于Python - 解决空页面中 Beautifulsoup 的 "object has no attribute"错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33406687/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com