【问题标题】:Python : Web scraping with Beautifulsoup - Why is the function get() not consistent?Python:使用 Beautifulsoup 进行 Web 抓取 - 为什么函数 get() 不一致?
【发布时间】:2020-12-10 16:54:54
【问题描述】:

我想创建一个瑞士公司的数据库,所以我在不同的 url 链接上迭代了一个“for”循环,如下所示:https://www.uid.admin.ch/Detail.aspx?uid_id=CHE106049755&lang=fr

我想得到这个页面的表格。

要遍历不同的链接,我只需更改链接的最后 9 个数字,因为“CHE---------”是瑞士特定公司的代码。但是,很少有代码没有归属,因此对于这些代码,我们在网站上有一条警告消息,如下所示: https://www.uid.admin.ch/Detail.aspx?uid_id=CHE106049555&lang=en

我认为我做了一个正确的脚本来创建我的数据库,但是我遇到了一个不是一行的问题:test = soup.find(id="alertError").get("style")

错误信息:"AttributeError: 'NoneType' object has no attribute 'get'"

当我说它不一致时,那是因为它有时出现在 2 个链接之后,其他时候出现 3 或 10 个。

我尝试通过test = soup.find(id="alertError")["style"] 切换函数“get()”,但它给出了同样的错误。我应该怎么做才能正确迭代?

谢谢

我的代码:

import requests
import pandas as pd
import numpy as np
import urllib.request
from bs4 import BeautifulSoup as bs

#### ====================================================================
#### -------------------------- INPUT -----------------------------------
#### ====================================================================

limit_down = 106049700
limit_up = 106049800

url_begin = "https://www.uid.admin.ch/Detail.aspx?uid_id=CHE"
url_end = "&lang=fr"

#### ====================================================================
#### -------------------DECLARATION OF VARIABLES ------------------------
#### ====================================================================

list_number = np.arange(limit_down, limit_up)

dfs = []

#### ====================================================================
#### ---------------------- CREATE LIST OF DATA -------------------------
#### ====================================================================

def get_data(bs_soup) :

    data_column = bs_soup.find(class_="tab-content").find_all(class_="col-sm-2 control-label")
    data_row = bs_soup.find(class_="tab-content").find_all(style="padding:7px 12px")

    l_columns = []
    l_rows = np.array([])

    for label in data_column :
        
        l_columns.append(label.get_text().strip())

    for label in data_row :
        
        l_rows = np.append(l_rows, (label.get_text().strip()))

    l_columns.remove("Acheminable")
    l_rows = l_rows.reshape(1, -1)

    return l_columns, l_rows

#### ====================================================================
#### --------------------------- EXECUTION ------------------------------
#### ====================================================================

for i in list_number :
    
    #### GET DATA OF THE WEBSITE
    url = str(url_begin) + str(i) + str(url_end)
    print("\nThe link : "  + str(url))

    response = requests.get(url)
    soup = bs(response.content, "lxml")

    #### CONTROL IF IT HAS THE DATA THAT WE WANT

    test = soup.find(id="alertError").get("style")

    if test == "display: none" :

        list_columns, list_rows = get_data(soup)

        df = pd.DataFrame(list_rows, columns= list_columns)
        dfs = dfs.append(df)

    elif test == "display:;" :

        print("The link does not concern a company")

        pass


df_final = pd.concat(dfs, ignore_index=True, sort=False)
df_final.to_excel("test_final")

【问题讨论】:

    标签: python xml pandas dataframe beautifulsoup


    【解决方案1】:

    错误说 The error message : "AttributeError: 'NoneType' object has no attribute 'get'" 表示页面上不存在该元素。

    您可以先检查元素是否存在。

    test = soup.find(id="alertError")
    
    if test:
        print("The link does not concern a company")        
    else:
        list_columns, list_rows = get_data(soup)
        df = pd.DataFrame(list_rows, columns=list_columns)
        dfs = dfs.append(df)
    

    【讨论】:

      猜你喜欢
      • 2021-04-07
      • 1970-01-01
      • 2019-01-09
      • 1970-01-01
      • 1970-01-01
      • 2018-09-22
      • 2020-10-04
      • 2015-03-29
      • 2021-01-31
      相关资源
      最近更新 更多