gpt4 book ai didi

python - 向 Python 的 NoneType 添加方法

转载 作者:太空宇宙 更新时间:2023-11-03 15:14:43 25 4
gpt4 key购买 nike

我正在使用 BeautifulSoup 进行一些爬行,并希望链接查找调用,例如:

soup.find('div', class_="class1").find('div', class_="class2").find('div', class_="class3")

当然,只要找不到其中一个 div,就会中断,抛出一个

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

有没有办法修改NoneType来增加一个find方法比如

class NoneType:
def find(*args):
return None

这样我就可以做类似的事情了

thing = soup.find('div', class_="class1").find('div', class_="class2").find('div', class_="class3")
if thing:
do more stuff

代替

thing1 = soup.find('div', class_="class1")
if thing1:
thing2 = thing1.find('div', class_="class2")
if thing2:
thing3 = thing2.find('div', class_="class3")
etc.

我想我可以通过使用具有 XPath 功能的解析器来做类似的事情,但这个问题并不特定于这个用例,更多的是关于修改/覆盖内置类。

最佳答案

为什么不改用 try/except 语句(因为您不能修改 NoneType)?

try:
thing = soup.find('div', class_="class1").find('div', class_="class2").find('div', class_="class3")
do more stuff
except AttributeError:
thing = None # if you need to do more with thing

关于python - 向 Python 的 NoneType 添加方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22313065/

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