【问题标题】:BeautifulSoup Exception mid loop scraping HTML fileBeautifulSoup 异常中循环抓取 HTML 文件
【发布时间】:2019-01-27 20:41:05
【问题描述】:

我正在尝试从 HTML 文件的本地文件夹中抓取几个变量,但在循环进行到一半时出现异常。例外是AttributeError: 'NoneType' object has no attribute 'contents。它实际上不是.contents 我查看了它挂起的文件,它的结构与其他文件完全相同。如果您删除.contents,那么您只需使用find() 函数引发相同的异常。有谁知道为什么会这样?再次,许多文件处理没有问题。我的代码如下:

df_list = []
folder = 'rt_html'
for movie_html in os.listdir(folder):
    with open(os.path.join(folder, movie_html)) as file:
        soup = BeautifulSoup(file)
        title = soup.find('title').contents[0][:-len(' - Rotten Tomatoes')]
        audience_score = soup.find('div', class_ = 'audience-score meter').find('span').contents[0][:-1]
        num_audience_ratings = soup.find('div', class_ = 'audience-info hidden-xs superPageFontColor')
        num_audience_ratings = num_audience_ratings.find_all('div') [1].contents[2].strip().replace(',', '')
    
    
        # print(num_audience_ratings)
        # break
           
        df_list.append({'title': title,
                        'audience_score': int(audience_score),
                        'number_of_audience_ratings': int(num_audience_ratings)})
df = pd.DataFrame(df_list, columns = ['title', 'audience_score', 'number_of_audience_ratings'])

【问题讨论】:

    标签: python beautifulsoup scrape


    【解决方案1】:

    我的猜测是某些文件没有您要查找的属性。

    例如。

     audience_score = soup.find('div', class_ = 'audience-score meter').find('span').contents[0][:-1]
    

    如果类 audience-score meter 中没有 div ,则 soup.find('div', class_ = 'audience-score meter') 将返回 None 。任何后续的findcontents 都将导致AttributeError

    一种解决方案是尝试除此之外并将值设置为空字符串。

    try:    
        audience_score = soup.find('div', class_ = 'audience-score meter').find('span').contents[0][:-1]
    except AttributeError:
        audience_score=""  
    

    titlenum_audience_ratings(两个作业)做同样的事情

    【讨论】:

    • Goo 故障排除建议。仍然不确定为什么会发生这种情况,我发现标签与循环中的其他文件相同。不过,这暂时可以解决,谢谢。
    猜你喜欢
    • 1970-01-01
    • 2017-08-26
    • 1970-01-01
    • 2019-12-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-07
    • 1970-01-01
    相关资源
    最近更新 更多