【问题标题】:Strange BeautifulSoup soup.findAll error: not working within functions奇怪的 BeautifulSoup soup.findAll 错误:不在函数内工作
【发布时间】:2016-01-13 20:03:13
【问题描述】:

我正在尝试构建一个非常简单的爬虫来收集链接,作为爬虫项目的一部分。我已经设置了以下函数来进行抓取:

import requests as rq 
from bs4 import BeautifulSoup

def getHomepageLinks(page):
    homepageLinks = []
    response = rq.get(page)
    text = response.text
    soup = BeautifulSoup(text)
    for a in soup.findAll('a'):
        homepageLinks.append(a['href'])
    return homepageLinks

我将此文件保存为“scraper2.py”。当我尝试运行代码时,出现以下错误:

>>> import scraper2 as sc
>>> sc.getHomepageLinks('http://washingtonpost.com')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "scraper2.py", line 9, in getHomepageLinks
    for a in soup.findAll('a'):
TypeError: 'NoneType' object is not callable

现在是奇怪的部分:如果我尝试调试代码并打印响应,它可以正常工作:

>>> response = rq.get('http://washingtonpost.com')
>>> text = response.text
>>> soup = BeautifulSoup(text)
>>> for a in soup.findAll('a'):
...     print(a['href'])
... 
https://www.washingtonpost.com
#
#
http://www.washingtonpost.com/politics/
https://www.washingtonpost.com/opinions/
http://www.washingtonpost.com/sports/
http://www.washingtonpost.com/local/
http://www.washingtonpost.com/national/
http://www.washingtonpost.com/world/
...

如果我正确阅读了错误消息,则说明 soup.findAll 会出现问题,但仅限于 findAll 是函数的一部分时。我确定我拼写正确(不是 findall 或 Findall,因为这里的许多错误都是如此),并且我已经尝试使用之前帖子中建议的 lxml 进行修复,但没有修复它。有人有什么想法吗?

【问题讨论】:

  • 作为健全性检查,print(soup.findAll) 就在导致错误的行之前。它是否打印None?如果是这样,print(soup) 和 print(type(soup)) 打印什么?
  • 尝试使用soup.find_all('a') 而不是soup.findAll('a')
  • 啊,对空白导入感到抱歉。我没有完全删除发布的一些旧代码的痕迹。立即编辑。
  • print(type(soup)) 在手动操作时返回“”。将其作为函数运行会在打印之前引发错误。
  • 我尝试了 find_all,但没有任何改变。据我了解,它们是可以互换的。

标签: python web-scraping beautifulsoup python-requests


【解决方案1】:

尝试用以下内容替换你的 for 循环:

for a in soup.findAll('a'):
    url = a.get("href")
    if url != None:
        homepageLinks.append(url)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-12-01
    • 2013-12-16
    • 1970-01-01
    • 1970-01-01
    • 2017-11-11
    • 2016-02-02
    • 1970-01-01
    • 2014-01-05
    相关资源
    最近更新 更多