2016-01-13 88 views
0

我试图建立一个非常简单的刮板收获链接作为一个履带项目的一部分。我已经设置了以下功能来进行拼图:奇怪的BeautifulSoup soup.find所有错误:功能内不工作

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建议上一篇文章没有解决它。有没有人有任何想法?

+0

作为一个全面的检查,'打印(soup.findAll)'权。它是否打印“无”?如果是这样,什么“打印(汤)”和“打印(类型(汤))”打印? – unutbu

+0

尝试使用'soup.find_all('a')'而不是'soup.findAll('a')' – gtlambert

+0

啊,对于空白导入感到抱歉。某些旧代码的遗留物,我没有完全删除发布。现在编辑。 – jtexnl

回答

0

尝试更换您的for循环有以下:导致错误的行前

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

不幸的是,它返回相同的错误。 – jtexnl