【问题标题】:Type error if link.has_attr('href'): TypeError: 'NoneType' object is not callable如果 link.has_attr('href') 出现类型错误:TypeError: 'NoneType' object is not callable
【发布时间】:2013-10-17 10:18:19
【问题描述】:

我试图执行以下 python 代码

import httplib2
from BeautifulSoup import BeautifulSoup, SoupStrainer

http = httplib2.Http()
status, response = http.request('http://www.nytimes.com')

for link in BeautifulSoup(response, parseOnlyThese=SoupStrainer('a')):
    if link.has_attr('href'):
        print link['href']

编辑: 我把代码改成了这个

for link in BeautifulSoup(response).find_all('a', href=True):
    print link['href']

但还是报同样的错误

我收到了错误

Traceback (most recent call last):
  File "/home/user1/Documents/machinelearning/extract_links.py", line 8, in <module>
    if link.has_attr('href'):
TypeError: 'NoneType' object is not callable

这个错误的原因是什么? 我该如何解决这个问题?

【问题讨论】:

    标签: python beautifulsoup


    【解决方案1】:

    您的列表返回一堆值以及其中的 None

    在我看来,你最好在这里使用find_all()

    for link in BeautifulSoup(response).find_all('a', href=True):
        print link['href']
    

    href=True 只会找到具有 href 值的标签,因此您不需要条件。

    【讨论】:

    • @Haido,相同的错误回溯(最近一次调用最后一次):文件“/home/user1/Documents/machinelearning/extract_links.py”,第 7 行,在 中用于 BeautifulSoup 中的链接(响应).find_all('a', href=True): TypeError: 'NoneType' 对象不可调用
    • @Haido,是的,你是真的
    • @karu 恐怕帮不了你:)。但很高兴我们解决了这个问题:)。所以BeautifulSoup() 正在做的是创造一些空的东西。 (即None
    • @Haido 是的,:) 对。问题仍然存在:)
    猜你喜欢
    • 2021-01-18
    • 1970-01-01
    • 2016-03-25
    • 2020-03-09
    • 2019-06-25
    • 2017-01-23
    • 2022-11-20
    • 2019-10-08
    相关资源
    最近更新 更多