有一個網站,我需要從在線游戲專案和研究中獲取該專案的所有者,我需要做一些“網路抓取”來獲取這些資料。但是,資訊位于 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
圖片鏈接
uj5u.com熱心網友回復:
要抓取 javascript 變數,不能只使用BeautifulSoup. 正則運算式 ( re) 是必需的。
使用ast.literal_eval以字典的轉換字串表示的字典。
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_data\s =\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, ...}
uj5u.com熱心網友回復:
import requests
import json
import re
r = requests.get('...')
m = re.search(r'var history_data\s =\s (.*)', r.text)
print(json.loads(m.group(1)))
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/383884.html
