【问题标题】:scrape data to store into pandas dataframe抓取数据以存储到熊猫数据框中
【发布时间】:2021-11-13 05:58:53
【问题描述】:

我正在尝试从这个网站https://en.wikipedia.org/wiki/List_of_chemical_elements刮掉表格“化学元素列表”

然后我想将表数据存储到 pandas 数据框中,以便我可以将其转换为 csv 文件。到目前为止,我已经将表的标题抓取并存储到数据框中。我还设法从表中检索每一行数据。但是,我无法将表的数据存储到数据框中。以下是我目前所拥有的

from bs4 import BeautifulSoup
import requests as r
import pandas as pd

response = r.get('https://en.wikipedia.org/wiki/List_of_chemical_elements')
wiki_text = response.text
soup = BeautifulSoup(wiki_text, 'html.parser')

table = soup.select_one('table.wikitable')

table_body = table.find('tbody')
#print(table_body)

rows = table_body.find_all('tr')

cols = [c.text.replace('\n', '') for c in rows[1].find_all('th')]

df2a = pd.DataFrame(columns = cols)
df2a

for row in rows:
    records = row.find_all('td')
    if records != []:
        records = [r.text.strip() for r in records]
        print(records)

【问题讨论】:

    标签: python pandas beautifulsoup


    【解决方案1】:

    在这里我找到了所有列数据,其中它分为两部分第一列和第二列数据

    all_columns=soup.find_all("tr",attrs={"style":"vertical-align:top"})
    first_column_data=[i.get_text(strip=True) for i in all_columns[0].find_all("th")]
    second_column_data=[i.get_text(strip=True) for i in all_columns[1].find_all("th")]
    

    现在我们需要 16 列,所以取适当的列并将数据添加到 new_lst 列表,即列列表

    new_lst=[]
    new_lst.extend(second_column_data[:3])
    new_lst.extend(first_column_data[1:])
    

    现在我们必须找到行数据遍历所有trattrs 并找到相应的td,它将返回表数据列表并附加到main_lst

    main_lst=[]
    for i in soup.find_all("tr",attrs={"class":"anchor"}):  
        row_data=[row.get_text(strip=True) for row in i.find_all("td")]
        main_lst.append(row_data)
    

    输出:

    Atomic numberZ  Symbol  Name    Origin of name[2][3]    Group   Period  Block   Standardatomicweight[a] Density[b][c]   Melting point[d]    Boiling point[e]    Specificheatcapacity[f] Electro­negativity[g]   Abundancein Earth'scrust[h] Origin[i]   Phase atr.t.[j]
    0   1   H   Hydrogen    Greekelementshydro-and-gen, 'water-forming' 1   1   s-block 1.008   0.00008988  14.01   20.28   14.304  2.20    1400    primordial  gas
    ....
    

    【讨论】:

      【解决方案2】:

      pandas为你解析:

      import pandas as pd
      
      df = pd.read_html('https://en.wikipedia.org/wiki/List_of_chemical_elements')[0]
      df.to_csv('file.csv', index=False)
      

      【讨论】:

        猜你喜欢
        • 2019-05-17
        • 2021-11-06
        • 2018-03-20
        • 2020-02-02
        • 1970-01-01
        • 1970-01-01
        • 2020-06-03
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多