使用python从javascript变量JSON.parse中提取数据

时间:2018-11-07 16:54:44

标签: javascript python json

对于python来说是新手,并试图通过Web抓取网站表,但是我认为表数据似乎来自带有JSON.parse的Javascript变量。但是解析不是我习惯的,并且不确定如何在python中使用它。

该代码来自this website,特别是var playersData = JSON.parse('\x5B\x7B\x22id\x3A,...(约250,000个字符)嵌套在脚本标签中。

到目前为止,我已经设法使用bs4抓取网站,找到特定的脚本,并尝试使用re.search仅查找JSON.parse并从搜索中找到此<re.Match object; span=(2, 259126), match="var playersData\t= JSON.parse('\\x5B\\x7B\\x22id\>

然后我想在加载JSON解析后将数据导出到其他地方。

到目前为止,这是我的代码:

import requests
from bs4 import BeautifulSoup
import json
import re

response = requests.get('https://understat.com/league/EPL/2018')
soup = BeautifulSoup(response.text, 'lxml')

playerscript = soup.find_all('script')[3].string
m = re.search("var playersData  = (.*)", playerscript)

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

您不需要BeautifulSoup。在python json.loads中与JSON.parse相同,并且您需要使用.decode('string_escape')bytes('....', 'utf-8').decode('unicode_escape')为python 3转换字符串

import requests
import json
import re

response = requests.get('https://understat.com/league/EPL/2018')
playersData = re.search("playersData\s+=\s+JSON.parse\('([^']+)", response.text)
# python 2.7
# decoded_string = playersData.groups()[0].decode('string_escape')
decoded_string = bytes(playersData.groups()[0], 'utf-8').decode('unicode_escape')
playerObj = json.loads(decoded_string)

print(playerObj[0]['player_name'])