python - 无法用 Beautiful Soup 解析 html 表

标签 python html pandas parsing beautifulsoup

我对使用 Beautiful Soup 很陌生,我正在尝试从以下网址导入数据作为 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)

最佳答案

您在表中看到的数据是通过 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 的屏幕截图):

enter image description here

关于python - 无法用 Beautiful Soup 解析 html 表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64198496/

相关文章:

javascript - jQuery 可拖动 "game"问题

Python - 与 __contains__ 相反

python - 使用 pandas 将数据框写入 Excel 是不正确的

python - OpenCV在图像上找到轮廓

Python——解析文件(docx、pdf 和 odt)并将内容转换为我的数据模型

html - 与 JSP 和 CSS 文件 float 对齐

python - Pandas 的滚动平均值

python - 顶点列表中的边 - gremlin python

python - 使用 `get_ancestors` 中的 `django-mptt` 函数时的错误结果

jquery - Bootstrap 3 : Panel collapsed by default