python - 为什么 Pandas Web Scraping 不能从该网站打印出任何表格?

标签 python pandas web-scraping

我用 pandas webscraping 编写了这个简单的代码,它应该从这个股票网站提取数据。但是,一旦我运行这段代码,它就会显示“列表索引超出范围”,这意味着该网站上没有任何表格。但是如果你打开网站,你可以清楚地看到有多个表。谁能解释一下我该如何解决它?

网站链接:https://www.hkex.com.hk/Products/Listed-Derivatives/Single-Stock/Stock-Options?sc_lang=en

import pandas as pd

url = 'https://www.hkex.com.hk/Products/Listed-Derivatives/Single-Stock/Stock-Options?sc_lang=en'
dfs = pd.read_html(url)

print(len(dfs)) #Gets the row count of the table

print(dfs[0]) #prints the first table 

最佳答案

从 Pandas 的角度来看,该页面中的表格存在一些不一致之处。这是将该页面上的第一个表作为数据框获取的一种方法:

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


headers = {
'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.5112.79 Safari/537.36'
}

url = 'https://www.hkex.com.hk/Products/Listed-Derivatives/Single-Stock/Stock-Options?sc_lang=en'

r = requests.get(url, headers=headers)
soup = bs(r.text, 'html.parser')
spec_table = soup.select('table[class="table migrate"]')[0]
df = pd.read_html(str(spec_table))[0]
print(df[:5].to_markdown())

这将返回数据框:

<表类="s-表"> <头> 否。 联交所代码 相关股票名称 HKATS 代码 合约大小(股) 棋盘数量 等级编号* 限仓##(2022年4月1日起生效) 台湾FSC认证 <正文> 0 1 16 新鸿基地产发展有限公司 SHK 1000 2 1 50000 ✓ 1 2 175 吉利汽车控股有限公司 GAH 5000 5 1 100000 ✓ 2 3 268 金蝶国际软件集团股份有限公司 KDS 2000 2 1 50000 南 3 4 285 比亚迪电子国际有限公司 再见 1000 2 1 50000 南 4 5 288 万洲国际 WHG 2500 5 2 100000 南

[...]

如果您需要页面中的其他表格,只需使用 BeautifulSoup 隔离它们,然后使用 pandas 读取它们。 BeautifulSoup 文档:https://beautiful-soup-4.readthedocs.io/en/latest/index.html

Pandas 相关文档:https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_html.html

关于python - 为什么 Pandas Web Scraping 不能从该网站打印出任何表格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73676866/

相关文章:

python - 如何在 Windows 上用 Python (3) 读取/写入文件而不引入回车符?

python - 为什么这个测试函数不输出图像? pokeGAN 教程

python - Pandas 如何使用 dt 按月和年分组

python - 使用 BeautifulSoup 抓取 Web 数据

python - 如何从回调返回空结果并继续抓取?

python - 在 python 中使用 urllib2 和 Tor 拒绝连接

PythonAnywhere->ImportError 引发加载 nrpccms.newsroom.templatetags.blog_extras : No module named settings

python - 如何保持累计金额?

python - 访问 SQLAlchemy 的外键项

python - 如何更改 Pandas Dataframe 的形状(行号为 "L")?