zoukankan      html  css  js  c++  java
  • selenium + Python (3) -- xpath定位

    1. xpath属性定位

    xpath可以通过元素的id, name, class这些属性定位,如下:

    driver.find_element_by_xpath("//*[@id='kw']").send_keys("by_xpath")
    driver.find_element_by_xpath("//*[@name='wd']").send_keys("by_xpath")
    driver.find_element_by_xpath("//*[@class='s_ipt']").send_keys("by_xpath")
    

    2. xpath其他属性定位

    driver.find_element_by_xpath("//*[@autocomplete='off']").send_keys("by_xpath")
    

    3. xpath标签

    同一个属性同名较多的时候,可以指定标签,定位更准,如下:

    driver.find_element_by_xpath("//input[@id='kw']").send_keys("by_xpath")
    

    4. xpath层级

    如果一个元素的属性不是很明显,可以通过父元素来找它,如果父元素的属性也不是很明显,就通过父元素的父元素,即爷爷元素来找,如下

    # 通过父元素定位
    driver.find_element_by_xpath("//span[@id='s_kw_wrap']/input").send_keys("by_xpath")
    #通过爷爷元素定位
    driver.find_element_by_xpath("//form[@id='form']/span/input").send_keys("by_xpath")
    

    5. xpath索引

    如果一个元素它的兄弟元素跟它标签一样,这时候无法通过层级定位,可以通过索引定位,如下:

    driver.find_element_by_xpath("//select[@id='nr']/option[1]").click()
    driver.find_element_by_xpath("//select[@id='nr']/option[2]").click()
    driver.find_element_by_xpath("//select[@id='nr']/option[3]").click()
    

    这里索引是从1开始的,跟python的索引不一样。

    6. xpath逻辑运算

    xpath支持与(and)、或(or)、非(not),如下:

    driver.find_element_by_xpath("//*[@id='kw' and @autocomplete='off']").send_keys("by_xpath")
    

    7. xpath模糊匹配

    # 匹配文字
    driver.find_element_by_xpath("//*[contains(text(), 'hao123')]").click()
    # 匹配属性
    driver.find_element_by_xpath("//*[contains(@id, 'kw')]").click()
    # 匹配以什么开头
    driver.find_element_by_xpath("//*[starts-with(@id, 's_kw_')]").click()
    # 匹配以什么结尾
    driver.find_element_by_xpath("//*[ends-with(@id, 'kw_wrap')]").click()
    
  • 相关阅读:
    同时实现打开两个文件的内容
    《APUE》第四章笔记(4)
    《APUE》第四章笔记(3)
    《APUE》第四章笔记(2)
    《APUE》第四章笔记(1)
    约瑟夫环问题(报数问题)
    无符号十进制整数转换成任意进制数
    《APUE》第三章笔记(4)及习题3-2
    Edit Distance问题在两种编程范式下的求解
    Boyer and Moore Fast majority vote algorithm(快速选举算法)
  • 原文地址:https://www.cnblogs.com/Jadie/p/9064460.html
Copyright © 2011-2022 走看看