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()
    
  • 相关阅读:
    简易sql拼接工具类(使用StringBuilder实现)
    缓存工具类(使用ConcurrentMap集合实现)
    properties文档读取工具类
    【Codeforces Round #655 (Div. 2)】A-D
    【2020 杭电多校第四场】Go Running 最小点覆盖
    【2020 杭电多校第四场】1002 Blow up the Enemy
    【2020 HDU 多校训练第三场 1007 Tokitsukaze and Rescue】暴力删边&最短路
    【2020杭电多校第二场】Total Eclipse 思维+并查集
    【2020HDU多校】Lead of Wisdom 暴力
    【CF-1371 C-E2】
  • 原文地址:https://www.cnblogs.com/Jadie/p/9064460.html
Copyright © 2011-2022 走看看