【问题标题】:BeautifulSoup not working, getting NoneType errorBeautifulSoup 无法正常工作,出现 NoneType 错误
【发布时间】:2016-06-14 12:24:18
【问题描述】:

我正在使用以下代码(取自retrieve links from web page using python and BeautifulSoup):

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']

但是,我不明白为什么会收到以下错误消息:

Traceback (most recent call last):
  File "C:\Users\EANUAMA\workspace\PatternExtractor\src\SourceCodeExtractor.py", line 13, in <module>
    if link.has_attr('href'):
TypeError: 'NoneType' object is not callable

美汤 3.2.0 Python 2.7

编辑:

我尝试了可用于类似问题的解决方案(Type error if link.has_attr('href'): TypeError: 'NoneType' object is not callable),但它给了我以下错误:

Traceback (most recent call last):
  File "C:\Users\EANUAMA\workspace\PatternExtractor\src\SourceCodeExtractor.py", line 12, in <module>
    for link in BeautifulSoup(response).find_all('a', href=True):
TypeError: 'NoneType' object is not callable

【问题讨论】:

  • @DavidZemens 重复的问题尚未解决。请查看该问题中的 cmets。
  • 重复的问题有一个可接受的答案,它可以确定您收到错误的为什么。考虑一些额外的调试,并根据需要使用try/except...
  • 另外,您是否尝试过该答案中提出的方法?
  • @DavidZemens 是的,请参阅我的编辑。此外,如果您会在原始问题中看到 cmets,那么您就会知道 OP 没有得到解决方案。 “@Haido 是的,:) 对。问题仍然存在 :) – karu”

标签: python html python-3.x beautifulsoup html-parsing


【解决方案1】:

首先:

from BeautifulSoup import BeautifulSoup, SoupStrainer

您正在使用 不再维护BeautifulSoup version 3。切换到BeautifulSoup version 4。通过以下方式安装:

pip install beautifulsoup4

并将您的导入更改为:

from bs4 import BeautifulSoup

还有:

Traceback(最近一次调用最后一次): 文件“C:\Users\EANUAMA\workspace\PatternExtractor\src\SourceCodeExtractor.py”,第 13 行,在 如果 link.has_attr('href'): TypeError: 'NoneType' 对象不可调用

这里的link 是一个Tag 实例,它没有has_attr 方法。这意味着,记住 dot notation means in BeautifulSoup 是什么,它会尝试在 link 元素内搜索元素 has_attr,但结果却一无所获。换句话说,link.has_attrNone,显然None('href') 会导致错误。

改为:

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

仅供参考,这是我用来调试您的问题的完整工作代码(使用requests):

import requests
from bs4 import BeautifulSoup, SoupStrainer


response = requests.get('http://www.nytimes.com').content
for link in BeautifulSoup(response, parseOnlyThese=SoupStrainer('a', href=True)).find_all("a", href=True):
    print(link['href'])

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-11-18
    • 2021-02-08
    • 1970-01-01
    • 2022-11-14
    • 2022-07-22
    • 2019-09-11
    • 1970-01-01
    相关资源
    最近更新 更多