【问题标题】:Trying to generate an AttributeError without success尝试生成 AttributeError 没有成功
【发布时间】:2016-03-16 21:06:22
【问题描述】:

我希望能够在最长的代码上过滤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)

我正在运行 Python 3.4.3

【问题讨论】:

  • 你的错误处理代码在哪里?
  • @Mike-Müller,这是终端的摘录,这是我的问题,我没有错误代码,我不明白为什么:nidupmtl:~/workspace/scrapingEnv $ source bin/activate (scrapingEnv)nidupmtl:~/workspace/scrapingEnv $ python test1.py None
  • 好的。这有帮助。添加了答案。

标签: python beautifulsoup attributeerror


【解决方案1】:

如果我理解您的要求,这就是您可以捕获AttributeError 的方法。

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

【讨论】:

    【解决方案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

    【讨论】:

    • @Nidupb 这对你有意义吗?
    猜你喜欢
    • 2017-12-13
    • 2019-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-29
    • 1970-01-01
    相关资源
    最近更新 更多