第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問題,去搜搜看,總會(huì)有你想問的

使用 beautifulsoup 從 <script> 中提取數(shù)據(jù)

使用 beautifulsoup 從 <script> 中提取數(shù)據(jù)

Qyouu 2021-09-02 16:44:50
我正在嘗試使用 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)


查看完整回答
反對 回復(fù) 2021-09-02
?
紫衣仙女

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ī)范


查看完整回答
反對 回復(fù) 2021-09-02
  • 2 回答
  • 0 關(guān)注
  • 965 瀏覽
慕課專欄
更多

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號