美文网首页
selenium-xpath定位

selenium-xpath定位

作者: 0981b16f19c7 | 来源:发表于2019-08-20 09:19 被阅读0次

    XPATH定位

    XPATH和CSS选择器最重要的区别是XPATH可以向前和向后查询DOM结构的元素,而CSS选择器只能向前查询,这意味着XPATH可以通过子元素来定位父元素!
    示例:

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
        <div id ='app'>我是div
            <form id="loginForm" name="f"> 我是form
                <input id="name" name="username" class="'s_ipt" autocomplete="off"> 我是input_1
                <input name="contiune" type="button">我是input_2
                <input type="submit" id="su" value="搜索" class="bg s_btn">我是input_2
            </form>
        </div>
    </body>
    </html>
    

    选取节点

    1)选取此节点下的所有子节点
    nodename = "html"
    element = driver.find_element_by_xpath("html").find_element_by_xpath('body')
    选取html-body节点下的所有子节点
    2) / 从根节点选取,代表绝对路径
    element = driver.find_element_by_xpath('/html/body/div')
    选取html-body-div节点下的所有子节点
    3)// 从匹配选择的当前节点选择文档中的节点,而不考虑它们的位置
    element = driver.find_element_by_xpath('//div')
    选取div节点下的所有子节点
    4). . 选取当前节点的父节点;@选取属性
    element = driver.find_element_by_xpath('//*[@id="name"]').find_element_by_xpath('..')
    选取input_1的父节点form
    5). 选取当前节点

    选取未知节点

    1)* 匹配任何元素节点
    element = driver.find_element_by_xpath('//[@id="name"]')
    //
    [@id="name"]:选取文档中所有符合id属性值为name的节点
    2)@* 匹配任何属性节点
    element = driver.find_element_by_xpath('//input[@*]')
    选取文档中所有带有属性input的元素
    3)node() 匹配任何类型的节点

    选取若干路径

    1) | 选取若干路径
    element = driver.find_element_by_xpath('//input| //div')
    选取文档中所有input和div元素

    关键字

    element = driver.find_element_by_xpath("//input[starts-with(@id,'na')]")
    选取id值以na开头的input节点
    element = driver.find_element_by_xpath("//input[contains(@id,'na')]")
    选取id值包含na的input节点
    element = driver.find_element_by_xpath("//input[contains(@id,'na') and contains(@id,'me')]")
    选取id值包含na和me的input节点
    element = driver.find_element_by_xpath("//title[contains(text(),'itle')]")
    选取节点文本包含itle的title节点

    xpath轴

    轴.png

    element = driver.find_element_by_xpath("//form/descendant::input[@id='name']")
    在form元素的所有子元素中,选择input标签且id为name的元素
    element = driver.find_element_by_xpath("//form/ancestor::div[@id='app']")
    在form元素的所有先辈中,选择div标签且id为app的元素

    XPATH使用方法:
    1、通过绝对路径定位(不推荐)
    2、通过相对路径定位
    3、通过索引定位
    element = driver.find_element_by_xpath("//input[1]")
    4、使用XPATH及属性值定位
    element = driver.find_element_by_xpath('//*[@id="name"]')
    5、使用XPATH及属性名称定位
    driver.find_element_by_xpath("//input[@id='name']")
    6、部分属性值匹配
    element = driver.find_element_by_xpath("//input[starts-with(@id,'na')]")
    7、使用任意值来匹配属性及元素
    8、使用XPATH轴来定位
    element = driver.find_element_by_xpath("//form/ancestor::div[@id='app']")

    相关文章

      网友评论

          本文标题:selenium-xpath定位

          本文链接:https://www.haomeiwen.com/subject/rchesctx.html