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)
相关推荐
小白编码4 小时前
【postMan / apifox 文件上传】
测试工具·postman
BatyTao12 小时前
当没有接口文档时,如何使用Jmeter录制和创建脚本
测试工具·jmeter
小白学大数据1 天前
构建企业级Selenium爬虫:基于隧道代理的IP管理架构
爬虫·tcp/ip·selenium
华科云商xiao徐1 天前
详解Selenium爬虫部署七大常见错误及修复方案
爬虫·selenium
别来无恙1492 天前
使用Python和Selenium进行Web自动化测试:从入门到实践
selenium·测试工具
Python大数据分析@2 天前
python用selenium怎么规避检测?
开发语言·python·selenium·网络爬虫
ThreeAu.2 天前
Miniconda3搭建Selenium的python虚拟环境全攻略
开发语言·python·selenium·minicoda·python环境配置
测试老哥2 天前
6个步骤实现Postman接口压力测试
自动化测试·软件测试·测试工具·测试用例·接口测试·压力测试·postman