Startswith的回溯错误

时间:2018-08-26 05:14:30

标签: python beautifulsoup

到达脚本末尾时,我不断收到回溯错误,提示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)

2 个答案:

答案 0 :(得分:1)

a标签在html 5中不能包含href,因此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属性,则该元素代表一个占位符,表示如果没有关联,则可能已放置了链接,该链接仅由元素的内容组成。

答案 1 :(得分:1)

您面临的问题是因为您尝试使用startswith运算符,而不管该值是否存在。您应该首先检查each变量是否具有值。试试这个

for each in s_names:
    if each and each.startswith('/401k'):
        final_url.append(each)

以上语句的作用是,首先检查值是否为None。然后,如果该值不是None,那么它将向前移动以使用startswith

进行检查
相关问题