Selenium爬蟲遇到 數據是以 JSON 字符串的形式包裹在 Script 標簽中,
假設Script標簽下代碼如下:
1
2
3
4
5
6
7
8
9
10
11
12
|
<script id= "DATA_INFO" type= "application/json" > { "user" : { "isLogin" : true , "userInfo" : { "id" : 123456, "nickname" : "LiMing" , "intro" : "人生苦短,我用python" } } } </script> |
此時drive.find_elements_by_xpath('//*[@id="DATA_INFO"] 只能定位到元素,但是無法通過.text方法,獲取Script標簽下的json數據
1
2
3
4
5
6
7
8
9
10
|
from bs4 import BeautifulSoup as bs import json as js #selenium獲取當前頁面源碼 html = drive.page_source #BeautifulSoup轉換頁面源碼 bs = BeautifulSoup(html, 'lxml' ) #獲取Script標簽下的完整json數據,并通過json加載成字典格式 js_test = js.loads(bs.find( "script" ,{ "id" : "DATA_INFO" }).get_text()) #獲取Script標簽下的nickname 值 js_tes |
到此這篇關于Selenium+BeautifulSoup+json獲取Script標簽內的json數據的文章就介紹到這了,更多相關Selenium+BeautifulSoup獲取json內容請搜索服務器之家以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持服務器之家!
原文鏈接:https://blog.csdn.net/qq_35866846/article/details/106348732