从html中的嵌入式脚本标签中提取数据

时间:2019-09-04 20:38:11

标签: python-3.x web-scraping beautifulsoup

我正在尝试在HTML的script标签中获取数据。通过使用Beautifulsoup,我可以使用必要的script,但无法获取所需的数据。

我在此标记内寻找的内容更具体地位于一个名为“ 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)

1 个答案:

答案 0 :(得分: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])