• python应用(二、Xpath定位web元素)


    2 Xpath定位web元素
    参考:https://www.bilibili.com/medialist/play/ml825155967/BV1ty4y1C74b
    2.1 web自动化定位元素的8种方法:
    1)id
    2)name
    3)class
    4)tagname
    5)linktext
    6)patiallinktext
    7)xpath
    8)cssselector

    2.2 xpath定位的方法
    2.2.1 xpath使用绝对位置定位
    从根目录(/)开始,一级一级找到目标路径
    1)查看html代码

    2)定位元素的html代码

    3)复制元素的xpath绝对路径

    获取到的xpath绝对路径:
    /html/body/div[1]/div[1]/div[5]/div/div/form/span[1]/input
    driver.find_element_by_xpath("/html/body/div[1]/div[1]/div[5]/div/div/form/span[1]/input")
    缺点:页面代码修改后,绝对路径改变的几率很大,很可能需要重新修改测试代码。

    2.2.2 xpath使用相对位置定位
    从//开始,从选择的元素集去找目标元素

    相对路径://form/span/input
    driver.find_element_by_xpath("//form/span/input").send_keys("自动化测试")
    缺点:当有多个同名标签时,无法正确定位。

    2.2.3 xpath使用索引定位
    标签[第几个]

    input在form里面第一个span中://form/span[1]/input
    driver.find_element_by_xpath("//form/span[1]/input").send_keys("自动化测试")
    缺点:页面代码修改后,可能需要重新修改测试代码。

    2.2.4 xpath使用属性值定位

    先找到//input,再用[]中的属性值约束input, //input[@id='kw']
    1)使用id属性:
    driver.find_element_by_xpath("//input[@id='kw']").send_keys("自动化测试")
    2)使用name属性
    driver.find_element_by_xpath("//input[@name='wd']").send_keys("自动化测试")
    3)使用class属性
    driver.find_element_by_xpath("//input[@class='s_ipt']").send_keys("自动化测试")
    4)使用多个属性定位元素,多个属性之间用and或or连接
    driver.find_element_by_xpath("//input[@id='kw' and @class='s_ipt']").send_keys("自动化测试")
    注意:
    1)确保标签值+属性值要唯一;
    2)有些程序运行时id会改变。

    2.2.5 xpath使用部分属性值定位(调用函数)

    函数:
    1)contains(@属性名,属性值) # 模糊匹配属性值
    autocomplete属性值包含'ff':
    driver.find_element_by_xpath("//input[contains(@autocomplete,'ff')]").send_keys("自动化测试")

    2)substring(@属性,n)=部分属性值 # n指的是开始截取的下标
    substring属性值从第3个字符到最后的值 = 'ipt':
    driver.find_element_by_xpath("//input[substring(@class,3)='ipt']").send_keys("自动化测试")

    3)starts-with(@属性名,属性值) # 属性值以什么开头
    class属性值以's_'开始:
    driver.find_element_by_xpath("//input[starts-with(@class,'s_')]").send_keys("自动化测试")

    2.2.6 xpath使用文本定位
    函数:text()

    点击“新闻”按钮
    首先通过id定位div(//div[@id='s-top-left']),再通过[text()='新闻']定位a标签。
    driver.find_element_by_xpath("//div[@id='s-top-left']/a[text()='新闻']").click()

  • 相关阅读:
    设置eclipse控制台上的信息输入到某个文件
    [HTML]去除li前面的小黑点,和ul、LI部分属性[转]
    fscanf函数的应用
    VC++中编译C出错:error C2143: syntax error : missing ';' before 'type'
    eclipse console输出有长度限制
    jstl之核心标签
    vmware esxi 6.0 开启嵌套虚拟化
    Proxmox如何进入单人维护模式(重置root密码)
    jstl错误排除:According to TLD or attribute directive in tag file, attribute value does not accept any expressions
    EL表达式
  • 原文地址:https://www.cnblogs.com/bdzxh/p/14171192.html
Copyright © 2020-2023  润新知