有没有一种方法可以从javascript文档中提取列表



有一个网站,我需要从一个在线游戏项目中获得该项目的所有者,通过研究,我需要做一些"网络抓取"来获得这些数据。但是,信息是在Javascript文档/代码中的,不是像bs4那样易于解析的HTML文档,这表明我可以轻松地从中提取信息。因此,我需要在这个javascript文档中获取一个变量(包含我正在查看的项目的所有者列表(,并将其变成一个可用的列表/json/string,我可以在程序中实现。有什么办法我能做到这一点吗?如果是,我该怎么办?

我已经附上了一张我在查看我所在网站的页面来源时需要的变量的图像。

我当前的代码:

from bs4 import BeautifulSoup
html = requests.get('https://www.rolimons.com/item/1029025').content #the item webpage
soup = BeautifulSoup(html, "lxml")
datas = soup.find_all("script")
print(data) #prints the sections of the website content that have ja

图像链接

要抓取javascript变量,不能只使用BeautifulSoup。正则表达式(re(是必需的。

使用ast.literal_eval将dict的字符串表示转换为dict。

from bs4 import BeautifulSoup
import requests
import re
import ast
html = requests.get('https://www.rolimons.com/item/1029025').content #the item webpage
soup = BeautifulSoup(html, "lxml")
ownership_data = re.search(r'ownership_datas+=s+.*;', soup.text).group(0)
ownership_data_dict = ast.literal_eval(ownership_data.split('=')[1].strip().replace(';', ''))
print(ownership_data_dict)

输出:

> {'id': 1029025, 'num_points': 1616, 'timestamps': [1491004800,
> 1491091200, 1491177600, 1491264000, 1491350400, 1491436800,
> 1491523200, 1491609600, 1491696000, 1491782400, 1491868800,
> 1491955200, 1492041600, 1492128000, 1492214400, 1492300800,
> 1492387200, 1492473600, 1492560000, 1492646400, 1492732800,
> 1492819200, ...}
import requests
import json
import re
r = requests.get('...')
m = re.search(r'var history_datas+=s+(.*)', r.text)
print(json.loads(m.group(1)))

最新更新