我正在嘗試使用 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)閱讀了這個回復(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")理想情況下,我會這樣做:json_dict = json.loads(raw_data)并通過字典訪問數(shù)據(jù)。但這不起作用,因為"<script> dataLayer =" 在有效的 json 之前,最后是 script 標(biāo)簽。我試過將 raw_data 修剪為字符串,如下所示:raw_data[20:]但這不起作用,因為湯對象不是字符串。如何讓 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)驗 獲得超11個贊
用于.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)驗 獲得超15個贊
>>> import re
>>> soup.find_all(re.compile("\[(.*?)\]"))
你會用正則表達(dá)式做到這一點(diǎn)
您將不得不創(chuàng)建一個只接受 [] 之間的文本的正則表達(dá)式規(guī)范
添加回答
舉報
0/150
提交
取消