首页 > 解决方案 > 带有startswith的回溯错误

问题描述

AttributeError: 'NoneType' object has no attribute 'startswith'当我到达脚本末尾时,我不断收到回溯错误。到目前为止,我正在做的是抓取各种不同的页面,然后将所有这些不同的页面拉到一个列表中,该列表会抓取每个业务页面的最终 URL。我所做的是去each_page并刮掉'a'页面上的所有标签,然后我想搜索它们并只保留以'/401k/'. 我知道我可能不需要将它添加到另一个列表中就可以做到,因为我觉得我有太多了。我正在考虑这样做:

for a in soup.findAll('a'):
    href = a.get('href')
    if href.startswith('/401k/'):
        final_url.append(href)
        #Even when I try this I get an error saying that no attribute 

无论哪种方式,它都没有获取数据,我无法弄清楚发生了什么。也许我一直在看屏幕太多。

import requests
from bs4 import BeautifulSoup

url = "https://www.brightscope.com/ratings/"
page = requests.get(url)
soup = BeautifulSoup(page.text, 'html.parser')
hrefs = []
ratings = []
pages = []
s_names = []
final_url = []

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)

del ratings[0]
del ratings[27:]

for each_rating in ratings:
    page = requests.get(each_rating)
    soup = BeautifulSoup(page.text, 'html.parser')
    span = soup.find('span', class_='letter-pages')
    if soup.find('span', class_='letter-pages'):
        for a in span.find_all('a'):
            href = a.get('href')
            pages.append('https://www.brightscope.com'+href)
    else:
        pages.append(page.url)
hrefs = []
pages = set(pages)
for each_page in pages:
    page = requests.get(each_page)
    soup = BeautifulSoup(page.text, 'html.parser')
    for a in soup.findAll('a'):
        href = a.get('href')
        s_names.append(href)
    # I am getting a traceback error AttributeError: 'NoneType' object has no attribute 'startswith' starting with the code below.
    for each in s_names:
        if each.startswith('/401k'):
            final_url.append(each)

标签: pythonbeautifulsoup

解决方案


ahref标签在 html 5 中可以没有,所以a.get('href')返回None. 这可能就是你正在经历的。
你需要的是确保你没有得到None

for a in soup.findAll('a'):
href = a.get('href')
if href is not None:
    s_names.append(href)

有关更多详细信息,请参见此处https://www.w3.org/TR/2016/REC-html51-20161101/textlevel-semantics.html#the-a-element

如果 a 元素没有 href 属性,则该元素代表一个占位符,用于放置链接,如果它是相关的,则仅包含元素的内容。


推荐阅读