抓取 href 不适用于 python

Scrape href not working with python

我有这段代码的副本,我正在尝试这样做,但每次我逐行复制它时,它都无法正常工作。我非常沮丧,似乎无法弄清楚它在哪里不起作用。我想做的是访问一个网站,废弃标有 A、B、C 等的不同评级页面。然后我将访问每个站点以提取他们正在使用的页面总数。我正在尝试抓取 <span class='letter-pages' href='/ratings/A/1' 等等。我究竟做错了什么?

import requests
from bs4 import BeautifulSoup
url = "https://www.brightscope.com/ratings/"
page = requests.get(url)
soup = BeautifulSoup(page.text, 'html.parser')
hrefs = []
ratings = []
ks = []
pages_scrape = []

for href in soup.findAll('a'):
    if 'href' in href.attrs:
        hrefs.append(href.attrs['href'])
for good_ratings in hrefs:
    if good_ratings.startswith('/ratings/'):
        ratings.append(url[:-9]+good_ratings)
# elif good_ratings.startswith('/401k'):
#     ks.append(url[:-9]+good_ratings)
del ratings[0]
del ratings[27:]
print(ratings)

for each_rating in ratings:
    page  = requests.get(each_rating)
    soup = BeautifulSoup(page.text, 'html.parser')
    for href in soup.find('span', class_='letter-pages'):
        #Not working Here
        pages_scrape.append(href.attrs['href'])
        # Will print all the anchor tags with hrefs if I remove the above comment.
        print(href)

您可能打算 find_all 而不是 find -- 所以更改

for href in soup.find('span', class_='letter-pages'):

for href in soup.find_all('span', class_='letter-pages'):

您想遍历 列表 标签,而不是单个标签。 find 会给你一个标签对象。当您迭代单个标签时,您迭代得到 NavigableString 个对象。 find_all 为您提供所需的标签对象列表。

您正试图过早地获取 href。您正在尝试直接从嵌套了 a 标签的 span 标签中提取属性,而不是从 a 标签列表中提取属性。

for each_rating in ratings:
    page  = requests.get(each_rating)
    soup = BeautifulSoup(page.text, 'html.parser')
    span = soup.find('span', class_='letter-pages')
    for a in span.find_all('a'):
        href = a.get('href')
        pages_scrape.append(href)

我没有在所有页面上测试它,但它适用于第一个页面。您指出某些页面上的内容没有被抓取,这是由于 span 搜索返回 None。要解决此问题,您可以执行以下操作:

for each_rating in ratings:
    page  = requests.get(each_rating)
    soup = BeautifulSoup(page.text, 'html.parser')
    span = soup.find('span', class_='letter-pages')
    if span:
        for a in span.find_all('a'):
            href = a.get('href')
            pages_scrape.append(href)
            print(href)
    else:
        print('span.letter-pages not found on ' + page)

根据您的用例,您可能想要做一些不同的事情,但这会告诉您哪些页面与您的抓取模型不匹配,需要手动调查。