【问题标题】:How to retrieve and store 2nd and 3rd row elements in a dataframe如何在数据框中检索和存储第二行和第三行元素
【发布时间】:2021-12-06 05:17:51
【问题描述】:

我是 Python 中 PandasWebscrapingBeautifulSoup 的新手。

当我学习通过使用requestsBeautifulSoup scrape 网页来使用 Python 进行一些基本的网页抓取时,我对分配网页的第二个和第三个元素的任务感到困惑将 html 表转换为 pandas 数据框。

假设我有这张桌子:

到目前为止,这是我的代码:

import pandas as pd
from bs4 import BeautifulSoup
import requests

html_data = requests.get('https://en.wikipedia.org/wiki/List_of_largest_banks').text
soup = BeautifulSoup(html_data, 'html.parser')
data = pd.DataFrame(columns=["Name", "Market Cap (US$ Billion)"])

for row in soup.find_all('tbody')[3].find_all('tr'): #This line will make sure to get to the third table which is this "By market capitalization" table on the webpage and finding all the rows of this table
  col = row.find_all('td') #This is to target individual column values in a particular row of the table
  for j, cell in enumerate(col):
    #Further code here

可以看出,我想定位一行的所有第 2 和第 3 列值并附加到 空数据框data,以便data 包含银行名称和市值值。我怎样才能实现这种功能?

【问题讨论】:

    标签: python pandas beautifulsoup python-requests


    【解决方案1】:

    对于表格,我建议pandas

    import pandas as pd
    url = 'https://en.wikipedia.org/wiki/List_of_largest_banks'
    tables = pd.read_html(url)
    df = tables[1]
    

    如果您更喜欢使用beautifulsoup,您可以尝试这样做:

    url = 'https://en.wikipedia.org/wiki/List_of_largest_banks'
    r = requests.get(url)
    soup = BeautifulSoup(r.content, 'html.parser').find_all('table')
    table = soup[1]
    table_rows = table.find_all('tr')
    table_header = [th.text.strip() for th in table_rows[0].find_all('th')]
    table_data = []
    for row in table_rows[1:]:
        table_data.append([td.text.strip() for td in row.find_all('td')])
    df = pd.DataFrame(table_data, columns=table_header)
    

    需要时,您可以将Rank 设置为索引df.set_index('Rank', inplace=True。下图是未修改的数据框。

    【讨论】:

    • 除了回答问题-> data = pd.read_html(url)[1].iloc[:,1:].iloc[:,1:] 将去除“排名”列
    • 对我来说似乎有点复杂:/
    猜你喜欢
    • 2018-10-19
    • 1970-01-01
    • 2015-04-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-14
    • 2021-12-13
    • 2011-06-18
    相关资源
    最近更新 更多