我正在嘗試使用 Python 和 Beautifulsoup 抓取一些數(shù)據(jù)。我知道如何從腳本標(biāo)簽中獲取文本。[ ] 之間的數(shù)據(jù)是有效的 json。<script> dataLayer = [ { "p":{ "t":"text1", "lng":"text2", "vurl":"text3" }, "c":{ }, "u":{ }, "d":{ }, "a":{ } }]</script>我已經(jīng)閱讀了這個(gè)回復(fù),它幾乎完成了我想要的: 用 BeautifulSoup 提取 <Script 的內(nèi)容這是我的代碼:import urllib.requestfrom bs4 import BeautifulSoupimport jsonurl = "www.example.com"html = urllib.request.urlopen(url)soup = BeautifulSoup(html, "html.parser")raw_data = soup.find("script")理想情況下,我會(huì)這樣做:json_dict = json.loads(raw_data)并通過字典訪問數(shù)據(jù)。但這不起作用,因?yàn)?quot;<script> dataLayer =" 在有效的 json 之前,最后是 script 標(biāo)簽。我試過將 raw_data 修剪為字符串,如下所示:raw_data[20:]但這不起作用,因?yàn)闇珜ο蟛皇亲址?。如何?raw_data 變量只包含塊引號 [ ] 之間的文本?編輯:這似乎有效。它避免了正則表達(dá)式并解決了尾隨字符的問題。感謝您的建議。url = "www.example.com"html = urllib.request.urlopen(url)soup = BeautifulSoup(html, "html.parser")# get the script tag data and convert soup into a stringdata = str(soup.find("script"))# cut the <script> tag and some other things from the beginning and end to get valid JSONcut = data[27:-13]# load the data as a json dictionaryjsoned = json.loads(cut)
2 回答

慕尼黑8549860
TA貢獻(xiàn)1818條經(jīng)驗(yàn) 獲得超11個(gè)贊
用于.text獲取<script>標(biāo)簽內(nèi)的內(nèi)容然后替換dataLayer =
raw_data = soup.find("script")
raw_data = raw_data.text.replace('dataLayer =', '')
json_dict = json.loads(raw_data)

紫衣仙女
TA貢獻(xiàn)1839條經(jīng)驗(yàn) 獲得超15個(gè)贊
>>> import re
>>> soup.find_all(re.compile("\[(.*?)\]"))
你會(huì)用正則表達(dá)式做到這一點(diǎn)
您將不得不創(chuàng)建一個(gè)只接受 [] 之間的文本的正則表達(dá)式規(guī)范
添加回答
舉報(bào)
0/150
提交
取消