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)
相关推荐
REDcker1 小时前
Puppeteer 与 Selenium 对比分析
爬虫·selenium·自动化·浏览器·puppeteer
我的xiaodoujiao1 小时前
使用 Python 语言 从 0 到 1 搭建完整 Web UI自动化测试学习系列 40--完善优化 Allure 测试报告显示内容
python·学习·测试工具·pytest
我的xiaodoujiao2 小时前
使用 Python 语言 从 0 到 1 搭建完整 Web UI自动化测试学习系列 41--自定义定制化展示 Allure 测试报告内容
python·学习·测试工具·pytest
玩转数据库管理工具FOR DBLENS3 小时前
人工智能:演进脉络、核心原理与未来之路 审核中
数据库·人工智能·测试工具·数据库开发·数据库架构
小罗和阿泽5 小时前
论坛系统测试报告
功能测试·测试工具·压力测试·可用性测试
写代码的【黑咖啡】17 小时前
Python中的Selenium:强大的浏览器自动化工具
python·selenium·自动化
可可南木20 小时前
3070文件格式--6--board文件格式详解 6
功能测试·测试工具·pcb工艺
程序员雷叔1 天前
在postman设置请求里带动态token,看看这两种方法!
selenium·测试工具·单元测试·测试用例·pytest·lua·postman
Hacker_xingchen1 天前
如何用Postman做接口自动化测试及完美的可视化报告?
自动化测试·软件测试·测试工具·职场和发展·postman
AI软件工程实践1 天前
软件工程里 Postman 的文件上传与下载测试技巧
测试工具·ai·lua·postman