Сергей Андреев Asked:2022-05-01 01:02:40 +0000 UTC2022-05-01 01:02:40 +0000 UTC 2022-05-01 01:02:40 +0000 UTC 如何从 <script> 标签中获取 Json 对象? 772 使用请求库,我在以下链接中获得一个页面:https ://pastebin.com/YneDr4id 如何获取写入到 initialState 变量的 Json 对象,以便在 python 代码中进一步使用该对象? javascript 1 个回答 Voted Best Answer Namerek 2022-05-01T07:54:24Z2022-05-01T07:54:24Z import json import re import requests from bs4 import BeautifulSoup as Soup response = requests.get( 'https://2gis.ru/voronezh/search/%D0%9F%D0%BE%D0%B5%D1%81%D1%82%D1%8C/firm/4363390420293667/39.202914%2C51.676518', headers={ "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:88.0) Gecko/20100101 Firefox/88.0" } ) soup = Soup(response.content, 'html.parser') script = soup.find( 'script', string=re.compile(r'^.*?var __customcfg.*$', flags=re.S) ).string.replace(r'\\"', r'\"') # Вот с этим уже можно работать dict_list = [*map(json.loads, map(lambda x: x.strip("'"), re.findall(r'\'.+?\'', script)))] # Это дамп для наглядности. Мне, к пиримеру, так проще разбирать словари json.dump( dict_list, open('j.json', 'w', encoding='utf-8'), ensure_ascii=False, indent=2 ) # Теперь про Нужный Вам контент: script = soup.find( 'script', string=re.compile(r'^.*?initialState = JSON.parse.*$', flags=re.S) ).string.replace(r'\\"', r'\"') initial_states_tag = re.search(r'initialState = JSON.parse.*?\'(.+?)\'', script).group(1) initial_states = json.loads(initial_states_tag) # Это даст вам искомый JSON в виде словаря в переменную initial_states 转储结果的字典列表将提供大约以下文件
转储结果的字典列表将提供大约以下文件