用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

相关推荐
程序员小远6 分钟前
接口测试和单元测试详解
自动化测试·软件测试·python·测试工具·单元测试·测试用例·接口测试
Ctrl С3 小时前
[三分钟]入门web自动化测试(一):1.使用驱动管理下载web驱动(WebDriver);2.初步认识和使用Selenium
selenium·测试工具·自动化·web
HtwHUAT4 小时前
二、UI自动化测试02--元素定位方法
笔记·python·selenium·ui
??? Meggie8 小时前
【Python】保持Selenium稳定爬取的方法(防检测策略)
开发语言·python·selenium
半路_出家ren1 天前
流量抓取工具(wireshark)
网络·网络协议·测试工具·网络安全·wireshark·流量抓取工具
猿周LV1 天前
JMeter 安装及使用 [软件测试工具]
java·测试工具·jmeter·单元测试·压力测试
西柚小萌新2 天前
【Python爬虫基础篇】--4.Selenium入门详细教程
爬虫·python·selenium
??? Meggie2 天前
Selenium 怎么加入代理IP,以及怎么检测爬虫运行的时候,是否用了代理IP?
爬虫·tcp/ip·selenium
天才测试猿2 天前
软件测试之功能测试详解
自动化测试·软件测试·python·功能测试·测试工具·职场和发展·测试用例
HtwHUAT2 天前
五、web自动化测试01
前端·css·chrome·python·功能测试·selenium·html