【问题标题】:Python 'NoneType' Object Has No Attribute 'attrs'Python 'NoneType' 对象没有属性 'attrs'
【发布时间】:2020-04-13 16:16:05
【问题描述】:

我正在对 Python 进行一些测试,并且一直在学习一些课程,但我现在非常卡住:

urls = []
for h3_tag in soup.find_all("h3"):
    a_tag = h3_tag.find('a')
    urls.append(a_tag.attrs['href'])
print(urls)

这应该得到一组 h3 中的“a”。确实如此,但是当我添加 .attrs['href'] 或 .text 以获取 URL Anchor 或 URL 本身时,我不断收到此错误: AttributeError: 'NoneType' object has no attribute 'attrs'

我似乎无法解决...

提前致谢

【问题讨论】:

  • 所有h3标签有锚点吗?
  • 不是全部,没有
  • find 如果没有找到该元素,则返回 None
  • 好的,所以你需要在尝试使用之前测试if a_tag is not None

标签: python beautifulsoup


【解决方案1】:

正如 chitown88 所述,您应该确保 h3_tag.find('a') 不会返回 None

但是,您应该避免使用不受限制的 tryexcept 语句来执行此操作。这会使将来的故障排除变得困难。我的版本的替代方法是在 except 子句之后简单地放置一个 KeyError。即except KeyError:

更多详情请看这里


这是我首选的处理方式

urls = []

for h3_tag in soup.find_all("h3"):
    # Get the a-tag or set a_tag to None if no a-tag is found
    a_tag = h3_tag.find('a')

    # Guarantee that we were able to find an a-tag
    if a_tag:        
        # Guarantee that the a_tag has an `href` attribute
        if a.get('href'):
            urls.append(a_tag.attrs['href'])

print(urls)

我希望这会有所帮助!

【讨论】:

  • should avoid doing it with unrestricted try and **except** statements。你能扩展一下吗?不想争论……只是想学习并不断改进。为什么你的解决方案是正确的?
  • 存在两种处理潜在异常的方法:一种称为 EAFP - 请求宽恕比请求许可更容易。另一个叫做 LBYL - 先看再跳。我不是在争论 EAFP 是否比 LBYL 更好或更差(尽管我更喜欢 LBYL)。没有争议的是 try-except 语句用于捕获特定错误。在您的 except 声明之后没有任何内容是不好的做法。如果你放了except KeyError(): .. 那会更有意义并且更有效。参考:python.org/dev/peps/pep-0463
  • 更多阅读请参见此处 - docs.python.org/3.3/tutorial/errors.html 来自文档的关于空的 except 子句的评论 The last except clause may omit the exception name(s), to serve as a wildcard. Use this with extreme caution, since it is easy to mask a real programming error in this way! It can also be used to print an error message and then re-raise the exception (allowing a caller to handle the exception as well):
  • 希望对您有所帮助!对不起,如果我遇到磨料。这不是我的意图。我只需要调试很多包含空 except 子句的代码,在进行故障排除时真的很糟糕。我总是建议多花一点时间来更详细一点。它将为下一个人省去很多麻烦。我已经更新了我的答案,说alternative way。很抱歉!
  • 哦,不,不!我没有把它当作磨料。我真的很想了解。那是有道理的。感谢回复!
【解决方案2】:

如果它没有找到a 标记,那么你就无法获得href 属性,即使它有一个。我会在这里合并一个 try/except ,或者如评论中所述,检查它是否是None

urls = []
for h3_tag in soup.find_all("h3"):
    try:
        a_tag = h3_tag.find('a')
        urls.append(a_tag.attrs['href'])
    except:
        continue
print(urls)

【讨论】:

  • 好的,所以这似乎有效......我想我是个菜鸟哈哈。谢谢!
  • 嘿,我们都是从菜鸟开始的!不用担心!继续学习、练习和提问!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-19
  • 2019-10-03
  • 2021-01-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多