用请求抓取网站,将javascript变量数据转换成python对象

2024-04-25 02:11:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在抓取一个网页,其中有一堆相关信息存储在javascript变量中

response = requests.get('')
r = response.text

r内部,有一个javascript变量,它有一堆我想要的数据

这是从服务器返回的内容:

<!DOCTYPE html>
<html>
<head>
....

<script>
 var candidate_details_input_string =  = '{ ...}'
</script>
....
</head>
</html>

candidate_details_input_string里面有一堆东西,我用.split()来隔离我想要的列表

x = r.split('candidate_completed_list\\":')[1].split(']')[0]+']'

不过,这会返回javascript字符串,但我使用的是Python。它看起来像这样:

x = '[{\\"i_form_name\\":\\"Applicant_Information_Form\\",\\"completed_time\\":\\"2017-02-03T19:12:00.000Z\\"},{\\"i_form_name\\":\\"Voluntary_Self_Identification_of_Disability_template\\",\\"completed_time\\":\\"2017-02-03T19:14:00.000Z\\"},{\\"i_form_name\\":\\"Voluntary_Self_Identification_of_Disability_template\\",\\"completed_time\\":\\"2017-02-05T19:21:00.000Z\\"},{\\"i_form_name\\":\\"Government_Entity_Questions_Form\\",\\"completed_time\\":\\"2018-07-03T00:29:00.000Z\\"}]'

这是一个javascript字符串,通常JSON.parse文件(),但不能,因为我正在用python刮它。你知道吗

有没有办法把它变成我可以使用的Python对象?我的默认答案是手工操作,替换所有\\并将'切换到"


Tags: 字符串nameforminputstringtimeresponsehtml
3条回答

在这种情况下,可以使用ast.literal_eval

data = '''<!DOCTYPE html>
<html>
<head>
....

<script>
 var candidate_details_input_string = '{"i_form_name":"Applicant_Information_Form"}';
</script>
....
</head>
</html>'''

import re
from ast import literal_eval

s = re.findall(r'var candidate_details_input_string\s*=\s*\'(.*?\})\s*\'\s*;', data, flags=re.DOTALL)[0]
data = literal_eval(s)
print(data)

印刷品:

{'i_form_name': 'Applicant_Information_Form'}

您正在从请求中获取JSON。尝试使用python的内置json库,您不必自己进行任何手动解析。你知道吗

import json
import requests

response = requests.get('')
r = todos = json.loads(response.text)

可以将x变量加载到json(字典)中。我们需要替换这些\,一切正常:

import json

x = '[{\\"i_form_name\\":\\"Applicant_Information_Form\\",\\"completed_time\\":\\"2017-02-03T19:12:00.000Z\\"},{\\"i_form_name\\":\\"Voluntary_Self_Identification_of_Disability_template\\",\\"completed_time\\":\\"2017-02-03T19:14:00.000Z\\"},{\\"i_form_name\\":\\"Voluntary_Self_Identification_of_Disability_template\\",\\"completed_time\\":\\"2017-02-05T19:21:00.000Z\\"},{\\"i_form_name\\":\\"Government_Entity_Questions_Form\\",\\"completed_time\\":\\"2018-07-03T00:29:00.000Z\\"}]'

data = json.loads(x.replace('\\',''))

print(data)

相关问题 更多 >