我用 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())
这将返回数据框:
[...]
如果您需要页面中的其他表格,只需使用 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/