用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

相关推荐
介一安全10 小时前
BurpSuite 插件 FastjsonScan 使用和手动验证
测试工具·网络安全·安全性测试·安全靶场
马克Markorg1 天前
使用rust实现的高性能api测试工具
开发语言·测试工具·rust·postman
介一安全2 天前
BurpSuite 插件 Log4j2Scan 使用和手动验证
测试工具·log4j·安全性测试
少云清2 天前
【UI自动化测试】3_web自动化测试 _Selenium-IDE
前端·selenium·web自动化测试
观音山保我别报错3 天前
抽奖项目-接口自动化测试
功能测试·测试工具·单元测试
我的xiaodoujiao3 天前
使用 Python 语言 从 0 到 1 搭建完整 Web UI自动化测试学习系列 48--本地环境部署Jenkins服务
python·学习·测试工具·pytest
我的xiaodoujiao3 天前
使用 Python 语言 从 0 到 1 搭建完整 Web UI自动化测试学习系列 49--CI/CD-开始探索使用Jenkins
python·学习·测试工具·ci/cd·jenkins·pytest
学习3人组4 天前
Win11 使用 Proxifier 强制本地流量通过 Fiddler Classic 代理指南
前端·测试工具·fiddler
少云清4 天前
【UI自动化测试】2_web自动化测试 _Selenium环境搭建(重点)
前端·selenium·测试工具·web自动化测试
少云清4 天前
【UI自动化测试】1_web自动化测试 _测试工具选择
测试工具·web自动化测试