用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

相关推荐
小陈的进阶之路13 小时前
Selenium元素定位
python·selenium
半个俗人15 小时前
06postman批量执行及参数化
测试工具·postman
紫丁香16 小时前
Selenium自动化测试详解1
python·selenium·测试工具·ui
软件测试君17 小时前
自动化测试路线图之自动化测试完整指南
自动化测试·软件测试·测试工具·面试·职场和发展·单元测试·职场经验
半个俗人19 小时前
05postman关联-常用的数据提取方式
测试工具·jmeter·postman·js
123过去21 小时前
ike-scan使用教程
linux·测试工具
半个俗人21 小时前
07.postman newman生成测试报告
测试工具·postman
爱敲代码的菜菜1 天前
【测试】自动化测试
css·selenium·测试工具·junit·自动化·xpath
123过去2 天前
wireshark使用教程
linux·网络·测试工具·wireshark
123过去2 天前
hexinject使用教程
linux·网络·测试工具