亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Python BeautifulSoup 如何從 javascript 元素中提取 var 結果?

Python BeautifulSoup 如何從 javascript 元素中提取 var 結果?

小唯快跑啊 2022-12-14 20:32:40
我是 Python 的新手,我一直在嘗試使用 BeautifulSoup 從腳本元素中定義的變量中提取一個特定的數據行。代碼:import requestsfrom bs4 import BeautifulSoupimport esprima#----------------some comment'URL = 'https://downdetector.com/status/facebook/'browser = {'user-agent': 'my agent'}#--------------some comment:page = requests.get(URL, headers=browser)soup = BeautifulSoup(page.content, 'html.parser')#---------------some comment:chart = soup.find("div",{"class":"popover-container justify-content-center p-relative"}).script.get_text()print(chart)輸出:var data = {status: 'success',  baseline: 29,       communicate: null,  company: 'Facebook',max: 66,series: [                      { x: '2020-05-30T13:22:28.168484-04:00', y: 25  },                      { x: '2020-05-30T13:37:28.168484-04:00', y: 27  },                      .....                      { x: '2020-05-31T13:07:28.168484-04:00', y: 30  },                  ]                }                $(function () {                  chartThis(data, 'holder', 'line')                });                if (data.communicate && $('#dd-communicate').length) {                  $('#dd-communicate').html('<div class="border text-left d-inline-block p-2"><i class="fa" aria-hidden="true" style="color: red; width:16px; height:12px; background:url(https://cdn2.downdetector.com/d328eb8cbe4e164/images/v2/message.svg) no-repeat"></i>'                    +'<span class="d-inline-block px-1">'+ data.company+' &bull;  ' + moment.utc(data.communicate.created_at).fromNow()                    + '</span><p class="font-weight-bold my-0">'+ data.communicate.message + '</p></div>')                }你知道從上面的 var 結果中提取“最大”值的簡單方法嗎?我試過使用 esprima,但仍然沒有成功,因為我遇到了錯誤:追溯(最近一次調用最后一次):文件“c:/test.py,第 31 行,在 if token[”type“] == “Identifier” and token [“value”] == “max”: TypeError: 'BufferEntry ' 對象不可訂閱
查看完整描述

1 回答

?
尚方寶劍之說

TA貢獻1788條經驗 獲得超4個贊

提取最大值的快速解決方案是split使用chart:


import requests

from bs4 import BeautifulSoup


URL = 'https://downdetector.com/status/facebook/'

browser = {'user-agent': 'my agent'}


page = requests.get(URL, headers=browser)

soup = BeautifulSoup(page.content, 'html.parser')



chart = soup.find("div",{"class":"popover-container justify-content-center p-relative"}).script.get_text()

max_val= chart.split("max: ")[1].split(",")[0]


print(max_val)


OUT: 64


查看完整回答
反對 回復 2022-12-14
  • 1 回答
  • 0 關注
  • 200 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號