奇怪的美人芬德尔汤错误:无法在函数中工作

2024-09-30 22:24:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图建立一个相当简单的刮板收获链接作为爬虫项目的一部分。我设置了以下函数来执行刮削:

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”。尝试运行代码时,出现以下错误:

^{pr2}$

如果我的代码行得通的话,那就试试打印这个代码吧:

>>> 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/
...

如果我正确地读取了错误消息,则问题发生在芬德尔汤,但仅当findAll是函数的一部分时。我确信我的拼写是正确的(不是findall或findall,因为这里有很多错误),而且我已经尝试过使用lxml的修复程序,在之前的一篇文章中没有修复它。有人有什么想法吗?在


Tags: 函数代码textimportcomhttpresponsewww
1条回答
网友
1楼 · 发布于 2024-09-30 22:24:25

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

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

相关问题 更多 >