ITPub博客

首页 > 数据库 > SQL Server > python_selenium元素定位_xpath(2)

python_selenium元素定位_xpath(2)

原创 SQL Server 作者:新梦想IT 时间:2023-01-06 15:10:44 0 删除 编辑

selenium自动化脚本最基础的就是元素定位和元素操作,下面就以百度为例介绍最常见的xpath定位方式


基本定位方式:


以百度的搜索框为例



from selenium import webdriver 

import time

driver = webdriver.Chrome()

driver.get("https://www.baidu.com")

driver.maximize_window()

time.sleep(2) 

# 1、绝对路径 

# driver.find_element_by_xpath("/html/body/div/div/div/div/div/form/span/input").send_keys("龙猫") 

# 2、相对路径 

# driver.find_element_by_xpath("//form/span/input").send_keys("龙猫") 

# 3、通过元素索引定位 

# driver.find_element_by_xpath("//div/div[3]/a[3]").click() 

# 4、使用元素属性定位 

# 4.1 单属性 

# driver.find_element_by_xpath("//input[@maxlength = '255']").send_keys("小狗") 

# 4.2 多属性and 

# driver.find_element_by_xpath("//input[@maxlength='255' and @autocomplete='off']").send_keys("小狗") 

# 4.3 多属性or 

# driver.find_element_by_xpath("//input[@maxlength='259' or @autocomplete='off']").send_keys("小狗") 

# 5、模糊匹配 

# 5.1 以什么开头starts-with() 

# driver.find_element_by_xpath("//a[starts-with(@name,'tj_trn')]").click() 

# 5.2 以什么结尾substring() 

# driver.find_element_by_xpath("//a[substring(@name,6)='news']").click() 

# 5.3 包含contains() 

# driver.find_element_by_xpath("//a[contains(@name,'trne')]").click() 

# 6、使用元素文本定位text()函数 

# driver.find_element_by_xpath("//a[text()='新闻']").click() 

driver.find_element_by_xpath("//a[contains(text(),'新')]").click()


这些就是xpath定位最常用的,至于怎么选择使用就看自己具体的使用情况了。


来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/69940641/viewspace-2931150/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论
新梦想IT职业教育(新梦想软件测试),是长沙一家专注于IT教育培训的机构。分享干货不容易,如果想了解更多的软件测试精彩干货,请留言交流,感谢阅读!

注册时间:2019-07-11

  • 博文量
    237
  • 访问量
    140169