python-3.x - 从html中的嵌入式脚本标签中提取数据

标签 python-3.x web-scraping beautifulsoup

我正在尝试在 HTML 中的(大)script 标记内获取数据。通过使用 Beautifulsoup,我可以接近必要的脚本,但我无法获得我想要的数据。

我在这个标签中寻找的东西位于一个名为“Beleidsdekkingsgraad”的列表中,更具体地说 ["Beleidsdekkingsgraad","107,6","107,6","109,1","109,8","110,1","111,5","112,5", "113,3","113,3","114,3","115,7","116,3","116,9","117,5","117,8","118 ,1","118,3","118,4","118,6","118,8","118,9","118,9","118,9","118,5 ","118,1","117,8","117,6","117,5","117,1","116,7","116,2"] 甚至更多具体的;列表中的最后一个条目 (116,2)

正在关注 12办不了案子。

到目前为止我做了什么

base='https://e.infogr.am/pob_dekkingsgraadgrafiek?src=embed#async_embed'
url=requests.get(base)
soup=BeautifulSoup(url.text, 'html.parser')
all_scripts = soup.find_all('script')
all_scripts[3].get_text()[1907:2179]

然而,这并不令人满意,因为每次添加新数字时都必须更改索引。

我正在寻找一种从 script 标记中提取列表的简单方法,其次是捕获提取列表的最后一个数字(即 116,2)

最佳答案

您可以用正则表达式输出保存该项目的 javascript 对象,然后使用 json 库进行解析

import requests,re,json

r = requests.get('https://e.infogr.am/pob_dekkingsgraadgrafiek?src=embed#async_embed')
p = re.compile(r'window\.infographicData=(.*);')
data = json.loads(p.findall(r.text)[0])
result = [i for i in data['elements'][1]['data'][0] if 'Beleidsdekkingsgraad' in i][0][-1]
print(result)

或者用正则表达式做所有事情:

import requests,re

r = requests.get('https://e.infogr.am/pob_dekkingsgraadgrafiek?src=embed#async_embed')
p = re.compile(r'\["Beleidsdekkingsgraad".+?,"([0-9,]+)"\]')
print(p.findall(r.text)[0])

第二个正则表达式:

enter image description here


另一种选择:

import requests,re, json

r = requests.get('https://e.infogr.am/pob_dekkingsgraadgrafiek?src=embed#async_embed')
p = re.compile(r'(\["Beleidsdekkingsgraad".+?"\])')
print(json.loads(p.findall(r.text)[0])[-1])

关于python-3.x - 从html中的嵌入式脚本标签中提取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57795346/

相关文章:

Python文本两个单词之间的解析

python - python 类中的输入检查函数

python - 使用 Beautiful Soup 查找跨度中的部分类名

python - 尝试从 html 表 python 添加某个值作为键并为该键添加多个值

javascript - 为什么源代码中看不到 DOM 结构?

Python Scrapy没有为每个链接执行scrapy.Request回调函数

javascript - 从外部网站获取内容?

python - 使用 python 重复数据删除库进行模糊重复检查错误

python-3.x - 文本检测 : Getting Bounding boxes

python-3.x - 在 Python 3.4 中随机化两个列表并维护顺序