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()
    
  • 相关阅读:
    (基础) --- KMP字符串
    (基础)--- 前缀和、差分
    PHOTOSHOP --- 分辨率、图片保存格式
    Oracle Delete数据后手动释放空间
    掌握爬虫技术需要学哪些内容?
    如何用python制作动态二维码,来哄女朋友开心?
    python为什么会环境变量设置不成功
    python和js交互调用的方法
    基于PHP实现解密或加密Cloudflar邮箱保护
    基于pytorch中的Sequential用法说明
  • 原文地址:https://www.cnblogs.com/Jadie/p/9064460.html
Copyright © 2011-2022 走看看