python - 由于无法选择表 id 属性,如何使用 BeautifulSoup 抓取表?

标签 python html beautifulsoup

我对 HTML 和网页抓取还很陌生。我一直在尝试从以下链接中抓取表格元素:

https://www.hkex.com.hk/Mutual-Market/Stock-Connect/Statistics/Hong-Kong-and-Mainland-Market-Highlights?sc_lang=en#select3=0&select2=2&select1=28

我想要做的是提取“总营业额”、“总市值”等元素。据我检查,所有这些元素都位于 <div class="table-container fixed-freeze-tb-parent" id="Tbl__0"> 中。 。

令我困惑的是,当我创建 BeautifulSoup 对象并使用

检索文本文件时
turn180329 = requests.get('https://www.hkex.com.hk/Mutual-Market/Stock-Connect/Statistics/Hong-Kong-and-Mainland-Market-Highlights?sc_lang=en#select3=0&select2=2&select1=28')
turnsoup = bs4.BeautifulSoup(turn180329.text,'lxml')`

`file180329 = open('180329.txt','wb')
for char in turn180329.iter_content(1000000):
    file180329.write(char)
file180329.close()

我可以选择div[class="table-container fixed-freeze-tb-parent"]返回 div元素但当我选择 id="tbl__0" 时什么也没返回使用

turn_table = turnsoup.find_all('#tbl__0.table-container fixed-freeze-tb-parent')

提取任何所需的表格元素。

对任何可以帮助我的人表示一百万的感激和感谢!!!

最佳答案

就像 @Juan Javier Santos Ochoa 所说,浏览器实际上发送另一个 URL,服务器用 JSON 数据响应该 URL。这是补充他的答案的代码部分。

可以修改此网址中的日期部分(TDD=29TMM=3TYYYY=2018)以获得以下结果不同的一天:

url = 'https://www.hkex.com.hk/eng/csm/ws/Highlightsearch.asmx/GetData?LangCode=en&TDD=29&TMM=3&TYYYY=2018'

感谢@Keyur Potdar 指出不需要发送 header 。

这是发送请求并获取 JSON 的行:

r = requests.get(url)
d = r.json()

结果如下:

# Turnover (Mil. shares) - Main Board, GEM
>>> print(d['data'][9]['td'][1])
['232,780', '1,769']

编辑:

  • 您可以使用 JSON Formatter 等在线服务了解 JSON 对象的结构。

关于python - 由于无法选择表 id 属性,如何使用 BeautifulSoup 抓取表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49630772/

相关文章:

python - 如何计算pandas中每个p1 id下的所有 child 的数量? id 和父 id 已给出

python - Centos 6.6 上的 mxnet 安装错误

javascript - 来自 JS Fiddle 的 JS 在浏览器测试中不起作用

python - 有条件地替换数据框列中的部分字符串

html - 如何为单个元素加载动画添加整页彩色背景?

javascript - 我的 CSS 样式表对我的 React 组件没有影响

Python-Beautiful Soup 不解析整个无序列表

python - Beautiful Soup - 打印容器文本而不打印子元素的文本

python - 如何使用 python 和 bs4 修复抓取 web 表输出 csv

python - 如何在pyspark中对数组中的标签进行编码