【问题标题】:unable to parse html table with Beautiful Soup无法用 Beautiful Soup 解析 html 表
【发布时间】:2020-10-04 18:38:19
【问题描述】:

我对使用 Beautiful Soup 非常陌生,我正在尝试从以下 url 导入数据作为 pandas 数据框。 但是,最终结果具有正确的列名,但没有行号。 我应该怎么做?

这是我的代码:

from bs4 import BeautifulSoup
import requests

def get_tables(html):
    soup = BeautifulSoup(html, 'html.parser')
    table = soup.find_all('table')
    return pd.read_html(str(table))[0]

url = 'https://www.cmegroup.com/trading/interest-rates/stir/eurodollar.html'
html = requests.get(url).content
get_tables(html)

【问题讨论】:

  • 您能否提供运行当前代码时所获得的输出。你也可以分享你想要的输出应该是什么。这将帮助我们为您提供一些提示。

标签: python html pandas parsing beautifulsoup


【解决方案1】:

您在表格中看到的数据是通过 JavaScript 从另一个 URL 加载的。您可以使用此示例将数据保存到 csv:

import json
import requests 
import pandas as pd

data = requests.get('https://www.cmegroup.com/CmeWS/mvc/Quotes/Future/1/G').json()

# uncomment this to print all data:
# print(json.dumps(data, indent=4))

df = pd.json_normalize(data['quotes'])
df.to_csv('data.csv')

保存data.csv(来自 LibreOffice 的屏幕截图):

【讨论】:

  • @Jojo 我查看了 Firefox 开发者工具 -> 网络选项卡(Chrome 也有类似的东西)。该页面正在执行所有请求。这些请求之一就是这个 Json 文件。
【解决方案2】:

您尝试从中抓取数据的网站正在动态呈现表值,使用 requests.get 只会返回服务器在 JavaScript 呈现之前发送的 HTML。 您将不得不找到访问数据或呈现网页 JS (see this example) 的替代方法。

执行此操作的常见方法是使用selenium 自动化浏览器,从而允许您呈现 JavaScript 并以这种方式获取源代码。

这是一个简单的例子:

import time 

import pandas as pd 
from selenium.webdriver import Chrome

#Request the dynamically loaded page source 
c = Chrome(r'/path/to/webdriver.exe')
c.get('https://www.cmegroup.com/trading/interest-rates/stir/eurodollar.html')

#Wait for it to render in browser
time.sleep(5)
html_data = c.page_source

#Load into pd.DataFrame 
tables = pd.read_html(html_data)
df = tables[0]
df.columns = df.columns.droplevel()    #Convert the MultiIndex to an Index 

注意我没用BeautifulSoup,你可以直接把html传给pd.read_html。您必须从那里进行更多清洁,但这就是要点。

或者,您可以在requests-html 上达到顶峰,这是一个提供 JavaScript 渲染的库,可能能够提供帮助,搜索从其他地方以 JSON 或 .csv 格式访问数据的方法并使用它等。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-07-03
    • 2022-12-02
    • 1970-01-01
    • 2014-12-16
    • 2011-09-27
    • 2017-07-20
    • 2015-11-08
    相关资源
    最近更新 更多