selenium中定位shadow-root,以及获取shadow-root内部的数据

通过shadow-root的父级定位到shadow-root,再通过语句进行操作

两种方法:

第一种,Python种JS实现

第二种,selenium实现

1.0 案例网站

参考某橘色网站

2.0 js语句定位

可在控制台进行测试

测试语句

bash 复制代码
document.querySelector("ali-bar-new").shadowRoot.querySelector("ali-bar-menu").shadowRoot.querySelector("div")

3.0 python实现js的方法

3.1 selenium实现

execute_实现

bash 复制代码
driver.execute_script('document.querySelector("ali-bar-new").shadowRoot.querySelector("ali-bar-menu").shadowRoot.querySelector("div")')

python直接实现

bash 复制代码
# example
root = driver.find_element("id", "form-shadow-root")
shadow_root = root.shadow_root
textfield = shadow_root.find_element_by_css_selector("div#dialog > div:nth-child(2) input")  # id为dialog的div的下一级div的第二个,之后的相对的input tag(无所谓层级)
btn = shadow_root.find_element_by_css_selector("button[class='btn next-button']") # tag为button的class为该值的元素
dropdown_item = shadow_root.find_element_by_css_selector('#search-field').find_element_by_xpath("//div//ul/li[text()='default']")  # 先找css然后再找sub element

3.2 python中直接调用执行js

3.2.1 基本操作

bash 复制代码
import js2py# 执行单行js语句
result = js2py.eval_js("console.log(abcd)")
print(result)
# 执行写在js文件中的
log = js2py.eval_js(open('./log.js','r',encoding='utf-8').read())
print(log)

js = js2py.EvalJs({})
js.execute("js语句")
bash 复制代码
import js2py
#创建js执行环境,返回一个上下文对象
content = js2py.EvalJs()
#执行js代码
#获取时间戳的js代码
js_text = '''
      var r = new Date().getTime()   
'''
content.execute(js_text)
print(content.r)
#执行js函数法二:
#会将文件中的代码添加到content对象中
content.execute(open('./log.js','r',encoding='utf-8').read())
print(content.需要执行的函数名('数据'))  #调用js代码中名为的函数

3.2.2 execjs实现

bash 复制代码
import execjs
js_code = open('file.js',encoding='utf-8').read()
ctx = execjs.compile(js_code)# 第一个参数为ja代码中的函数名, 后面为函数对应的参数
result = ctx.call('function_name', *args)
相关推荐
梧桐1683 小时前
14天、31个缺陷、28个测试脚本—用 Claude Code 完成第三方软件测试
人工智能·测试工具
mewowaBc11 小时前
postman使用细则
测试工具·postman·偏差
光影62721 小时前
Unittest单元测试基础速记
测试工具·单元测试·json·测试覆盖率
xie881018021 天前
正则里的点号不匹配换行:多行模式的开关
运维·服务器·测试工具
2601_967987372 天前
Python在自动化测试中有哪些应用?
python自动化测试·selenium·appium·pytest·性能测试
东舟技术2 天前
从人工目检到AI视觉:智能座舱瞬态故障的自动化捕获与溯源
功能测试·测试工具·自动化
小猿A3 天前
【2026最新】Apifox下载、配置、实战教程(附官网安装包)
测试工具
泽众云测试4 天前
泽众软件与广州华南检验检测中心签约,PerformanceRunner性能测试工具助力第三方测评机构性能检测能力升级
软件测试·测试工具·性能测试
@zulnger4 天前
Charles抓包工具
测试工具
ck0135794 天前
视频添加水印的实践:文字叠加、透明 PNG 与时间区间设置
图像处理·测试工具·音视频·视频