各种xpath定位方法以及xpath轴定位
from selenium import webdriver
import time
from selenium.webdriver.support.select import Select
from selenium.webdriver import ActionChains
from selenium.webdriver.common.keys import Keys
from Common.baseui import baseUI
'''
该脚本主要学习各种不同xpath元素定位的方法以及xpath轴定位
'''
def test_jd_demo1(driver):
driver.get("file:///C:/Users/52826/Desktop/index.html")
# 1.依靠自己属性,文本定位
text = driver.find_element_by_xpath("//a[contains(text(),'度娘')]")
text.click()
time.sleep(2)
driver.back()
time.sleep(2)
def test_jd_demo2(driver):
driver.get("file:///C:/Users/52826/Desktop/index.html")
# 1.混合型定位
text1 = driver.find_element_by_xpath("(//div[contains(@type,'password')])[2]/a")
text1.click()
time.sleep(2)
driver.back()
time.sleep(2)
def test_jd_demo3(driver):
driver.get("file:///C:/Users/52826/Desktop/index.html")
# 1.following-sibling “选择当前节点之后的所有同级节点”
text1 = driver.find_element_by_xpath("(//input[@type='checkbox']/following-sibling::input)[1]")
time.sleep(2)
text1.click()
time.sleep(2)
def test_jd_demo4(driver):
driver.get("file:///C:/Users/52826/Desktop/index.html")
# 1.preceding-sibling的解释是“选取当前节点之前的所有同级节点”
text1 = driver.find_element_by_xpath("//a[@href='http://www.dangdang.com/']/preceding-sibling::a")
time.sleep(2)
actions = ActionChains(driver)
actions.key_down(Keys.CONTROL).click(text1).key_up(Keys.CONTROL).perform()
time.sleep(2)
def test_jd_demo5(driver):
driver.get("file:///C:/Users/52826/Desktop/index.html")
# 1.last()的解释是“获取最后一个标签元素”
text1 = driver.find_element_by_xpath("//a[last()]") # //a[last()-1] 获取倒数第二个标签元素
time.sleep(2)
actions = ActionChains(driver)
actions.key_down(Keys.CONTROL).click(text1).key_up(Keys.CONTROL).perform()
time.sleep(2)
def test_jd_demo6(driver):
driver.get("file:///C:/Users/52826/Desktop/index.html")
# 1.starts-with的解释是“和字面意思一样就是以某某开头” 例如://input[starts-with(@class,'xxx')]
text1 = driver.find_element_by_xpath("(//a[starts-with(@href,'http://www.baidu.com')])[last()]")
time.sleep(2)
actions = ActionChains(driver)
actions.key_down(Keys.CONTROL).click(text1).key_up(Keys.CONTROL).perform()
time.sleep(2)
# 获取页面的全部句柄
handles = driver.window_handles
# 循环遍历当前页面的句柄
for handle in handles:
time.sleep(2)
# 循环跳转浏览器页面
driver.switch_to_window(handle)
# 获取页面的title
title = driver.title
# 判断预期值是否在title中, 满足就结束跳转,停留在当前页面
if '新闻' in title:
break
time.sleep(2)
//ul[starts-with(@id,"menu")]/li[2]
starts-with的意思是判断是否以什么为起始
((//ul[@class="el-scrollbar__view el-select-dropdown__list"])[last()]//span)[1]
选择对应的下拉选项值 last()取最后一个 ul@class的最后一个里的span第一个
xpath轴定位
following 后面的任意节点
*following-sibling 后面的同级节点
preceding 前面的任意节点
*preceding-sibling 前面的同级节点
*parent 父节点
ancestor 所有先辈节点
*child 子节点
descendant 所有后代节点
self 节点自己
image.png
例如:(//span[contains(text(),'外层 Dialog')])[2]/following-sibling::button/i
网友评论