用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

相关推荐
程序员杰哥3 小时前
Python自动化测试之线上流量回放:录制、打标、压测与平台选择
自动化测试·软件测试·python·测试工具·职场和发展·测试用例·压力测试
2501_924064114 小时前
2025数据库性能测试工具:Utest、JMeter、HammerDB 等主流方案推荐
数据库·测试工具·jmeter·数据库性能测试·数据库负载测试·数据库压测工具·jmeter 压力测试
卖个几把萌4 小时前
【08】JMeter从文本中读取多个参数
测试工具·jmeter
Sunhen_Qiletian11 小时前
python语言应用实战--------网络爬虫篇 第二篇(selenium库)
爬虫·python·selenium
inter_peng14 小时前
【DICOM网络问题】基于tcpdump和wireshark解决服务器无法连接打印机打印胶片的问题
测试工具·wireshark·tcpdump
BINGCHN14 小时前
流量分析入门(二):wireshark的使用
网络·测试工具·wireshark
卓码软件测评15 小时前
自动化软件API测试部署Postman和Jenkins集成
测试工具·自动化·jenkins·测试用例·postman·软件需求
陈辛chenxin15 小时前
【接口测试】Postman教程
python·selenium·测试工具·postman·可用性测试
程序员小远15 小时前
Postman详解
自动化测试·软件测试·python·测试工具·测试用例·接口测试·postman
2501_9159090615 小时前
iOS App 测试工具全景指南,构建从开发、性能到系统级调试的多工具协同测试体系
android·测试工具·ios·小程序·uni-app·iphone·webview