【问题标题】:Beautiful Soup scrape table with table breaks美丽的汤刮桌与餐桌休息
【发布时间】:2019-02-15 09:35:44
【问题描述】:

我正在尝试将table 抓取到数据框中。我的尝试只返回表名,而不是每个区域的行内的数据。

这是我目前所拥有的:

from bs4 import BeautifulSoup as bs4
import requests

url = 'https://www.eia.gov/todayinenergy/prices.php'
r = requests.get(url)
soup = bs4(r.text, "html.parser")

table_regions = soup.find('table', {'class': "t4"})
regions = table_regions.find_all('tr')

for row in regions:
    print row

我想要得到的理想结果:

region         | price   
---------------|-------
new england    | 2.59
new york city  | 2.52

感谢您的帮助。

【问题讨论】:

    标签: python dataframe web-scraping beautifulsoup


    【解决方案1】:

    如果您检查您的 html 响应(汤),您将看到您在此行中获得的表标签 table_regions = soup.find('table', {'class': "t4"}) 它在包含您需要的信息的行之前关闭(包含类名的 td 的行) : 上 dn d1 和 s1。 那么如何使用这样的原始 td 标签:

    from bs4 import BeautifulSoup as bs4
    import requests
    import pandas as pd
    
    url = 'https://www.eia.gov/todayinenergy/prices.php'
    r = requests.get(url)
    soup = bs4(r.text, "html.parser")
    
    a = soup.find_all('tr')
    rows = []
    subel = []
    
    for tr in a[42:50]:
        b = tr.find_all('td')
        for td in b:
            subel.append(td.string)
        rows.append(subel)
        subel = []
    
    df = pd.DataFrame(rows, columns=['Region','Price_1', 'Percent_change_1', 'Price_2', 'Percent_change_2', 'Spark Spread'])
    

    请注意,我只使用了结果的 a[42:50] 切片,因为 a 包含网站的所有 td。如果需要,您也可以使用其余部分。

    【讨论】:

    • 非常感谢您的指导。对行索引进行了微调以捕获所有记录 a[40:50] :)
    猜你喜欢
    • 2019-03-13
    • 1970-01-01
    • 2021-09-12
    • 2014-11-01
    • 2020-02-29
    • 1970-01-01
    • 1970-01-01
    • 2021-01-15
    相关资源
    最近更新 更多