用selenium和xpath定位元素并获取属性值以及str字符型转json型

页面html如图所示:

要使用xpath定位这个div元素,并且获取其属性data-config的内容值。

复制代码
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.options import Options

host='127.0.0.1'
port='10808'
chrome_options = Options()#如果是from selenium.webdriver.edge.options import Options,打开edge;如果是from selenium.webdriver.chrome.options import Options,打开chrome
chrome_options.add_argument("--proxy-server=socks5://" + host + ":" + port)

driver = webdriver.Chrome(options=chrome_options)
url = "https://xxxx.xxx/archives/1234/"
driver.get(url)
div =driver.find_element(By.XPATH,"//div[@class='dplayer dplayer-no-danmaku']")
str_attr=div.get_attribute('data-config')
print(str_attr)

import json
json_attr=json.loads(str_attr)
print(json_attr)
print(json_attr['video']['url'])

结果如图:

蓝色的为str类型,红色的为json类型。

那么先得到的是str类型,如何转换为json类型呢?使用如下代码即可。

import json

json_attr=json.loads(str_attr)

读取json数据用json_attr['video']['url']即可。具体可参阅这篇好文:

如何将 Python 字符串转换为 JSON

相关推荐
Wild_Pointer.9 小时前
高效工具实战指南:Beyond Compare文件比较工具
测试工具
Three~stone11 小时前
Wireshark 4.6.4 安装教程
网络·测试工具·wireshark
念越19 小时前
蓝桥杯自动化测试模拟1期答案及代码解析(完整版)
自动化测试·软件测试·selenium·蓝桥杯
Luminbox紫创测控1 天前
太阳光模拟器在汽车智能玻璃的运用
测试工具·汽车
西瓜程序猿1 天前
如何将纸质版礼薄转换为电子礼薄?可以使用记了么
测试工具·创业创新
123过去2 天前
crunch使用教程
linux·测试工具·安全
南通DXZ2 天前
Python爬虫进阶:Selenium模拟真人操作(解决反爬+动态网页)
爬虫·python·selenium
123过去2 天前
samdump2使用教程
linux·测试工具·安全
测试19982 天前
使用Python自动化生成接口测试用例
自动化测试·软件测试·python·测试工具·职场和发展·测试用例·接口测试