尝试生成AttributeError但未成功

2024-04-19 18:48:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我希望能够过滤最长代码上的AttributeError,但我不明白为什么它总是返回我None,而不是这个简单代码上的AttributeError?你知道吗

from urllib.request import urlopen
from bs4 import BeautifulSoup
html = urlopen("http://www.pythonscraping.com/pages/page1.html")
bsObj = BeautifulSoup(html.read(), "html.parser")
print(bsObj.randomtest)

我正在运行python3.4.3


Tags: 代码fromimportnonehttprequesthtmlwww
2条回答

深入到bs4的源头,你会找到原因。实现了BeautifulSoup的方法__getattr__,实际上是从Tag继承的。每次访问不存在的属性时都会调用此方法。这就是使用randomtest时发生的情况。此方法将被调用:

def find(self, name=None, attrs={}, recursive=True, text=None,
         **kwargs):
    """Return only the first child of this Tag matching the given
    criteria."""
    r = None
    l = self.find_all(name, attrs, recursive, text, 1, **kwargs)
    if l:
        r = l[0]
    return r

因此,如果它找不到任何东西,它将返回None。你知道吗

如果我理解你的要求,这就是你如何抓住一个AttributeError。你知道吗

try:
    ##Do whatever you want that could be caught by an error
except AttributeError:
        print("AttributeError")

相关问题 更多 >