首页 > 编程语言 >python_selenium元素定位_xpath(2)

python_selenium元素定位_xpath(2)

时间:2022-10-24 11:25:01浏览次数:36  
标签:xpath python selenium driver element click div find

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定位最常用的,至于怎么选择使用就看自己具体的使用情况了。

标签:xpath,python,selenium,driver,element,click,div,find
From: https://www.cnblogs.com/xmxit/p/16820846.html

相关文章

  • Python如何根据两个字段进行排序?
    Python如何根据两个字段进行排序?写这个博客,就是为了吐槽Python!对于这个问题,首先,我花了一天时间,没有解决!当然是百度了,一搜,有很多博客,无一例外,都是垃圾!有的,只排数组!实体......
  • 【Python基础学习】第十二节 文件操作
    Python基础学习之文件操作1.open()函数想要对文件进行操作,必须先建立文件对象,然后再对文件对象进行操作;想要建立文件对象,需要使用open()函数;open()函数使用方法如下:f......
  • 【Python基础学习】第十三节 异常操作总结
    Python基础学习之异常操作总结在Python运行遇到异常时,程序会终止;而在我们编程过程中,错误是不可避免的,这时我们需要捕捉到异常,还需要程序继续运行;这时我们就需要根据异常Tra......
  • Python&JS宏 实现保留样式合并表格后拆分
    ......
  • Python while循环
    1.简单的while循环【实例】:number=1whilenumber<=5:print(number)number+=1【运行结果】:12345 2.使用break退出循环【实例】:number=1......
  • python 中xlrd模块
    一、模块介绍    1、xlrd是用来操作读取excel表格的库,支持xlsx和xls两种格式    2、安装方式?pip3installxlrd    3、导入方式importxlrd......
  • python-Matplotlib
    Matplotlib:python的2D绘图库,可生成绘图/直方图/功率图/条形图/错误图/散点图等。Matplotlib被集成进Anaconda。网址:https://matplotlib.org一、绘制基础常用场景:画点、......
  • Python: Mediator Pattern
    DuMediator.py#中介者模式MediatorPattern#ParticipantReference:importsys'''classUser(object):def__init__(self,med,name):self.media......
  • 代码卡(python)
    1.打印 print(1024)2.注释 #thisisthefirstcode3.字符串 print("helloworld")4.赋值 Name="Tony"program="夜曲编程"......
  • Python: Iterator Pattern
    DuIterator.py#迭代器模式IteratorPattern#DoublyLinkedListclassNode(object):def__init__(self,value,nextNode,prevNode):self.value=......