selenium定位详解

复制代码
# 跳转到最新窗口
driver.switch_to.window(driver.window_handles[-1])

# 跳转到iframe,属性id,name,class均可
driver.switch_to.frame("passport_iframe")

# 根据class属性定位
driver.find_element(By.CLASS_NAME, "toolbar-btn-loginfun").click()

# 发布文章,根据带空格的class属性定位
driver.find_element(By.CSS_SELECTOR, ".button.btn-b-red.ml16").click()

# 根据文本内容定位,点击发布按钮
driver.find_element(By.LINK_TEXT, "发布").click()

#查找任意标签下,class=xxx的元素
driver.find_element(By.XPATH, "//*[@class='xxx']")

查找button标签下,class=xxx的元素
driver.find_element(By.XPATH, "//button[@class='xxx']")

查找button标签下,文本内容为"发布文章"并且class=xxx的元素
driver.find_element(By.XPATH, "//button[text()='发布文章' and class='xxx' ]")

查找button标签下,文本内容为"发布文章"并且class内包含xxx关键字的元素
driver.find_element(By.XPATH, "//button[text()='发布文章' and contains(@class,'xxx') ]")

查找button标签下,class属性中开始位置为'abcd'关键字的元素
driver.find_element(By.XPATH, "//button[starts-with@class,'abcd')]")

查找button标签下,class属性中结尾位置为'xyz'关键字的元素
driver.find_element(By.XPATH, "//button[end-with@class,'xyz' ]")


定位最后一个元素
driver.find_element(By.XPATH, "//button[last()]")
定位倒数第二个
driver.find_element(By.XPATH, "//button[last()-1]")

定位第一个text()="发布文章"
driver.find_element(By.XPATH, "//button[text()='发布文章' and position()=1 ]")

CSS_SELECTOR定位class带空格的元素
driver.find_element(By.CSS_SELECTOR, ".button.btn-b-red.ml16")
相关推荐
ClouGence21 小时前
不搭 Selenium 或 Playwright,怎么测试公司的内网业务?
selenium·测试
2601_967987379 天前
Python在自动化测试中有哪些应用?
python自动化测试·selenium·appium·pytest·性能测试
深蓝电商API10 天前
XPath、CSS选择器、正则:什么场景用什么
爬虫·xpath·css选择器
EVE จุ๊บ12 天前
playwright和selenium的区别是什么
selenium·测试工具
P1Browser17 天前
Puppeteer 与 Selenium 技术对比:多账号自动化管理如何做环境隔离?
selenium·测试工具·自动化
Data_Journal21 天前
如何使用 Selenium 和 Node.js 绕过 CAPTCHA
selenium
郝学胜-神的一滴21 天前
Python浏览器自动化:Selenium与Playwright实战对比,网页爬虫&自动操作一站式指南
开发语言·爬虫·python·selenium·程序人生·自动化
Wokoo723 天前
Selenium 核心 API 解析(三)
python·功能测试·selenium
技术人生00123 天前
Selenium 工程化模板(日志+异常截图,可直接复制使用)
python·selenium·测试工具
Wokoo723 天前
Selenium:元素定位、动态适配与性能优化(二)
前端·selenium·自动化