• SeleniumPython学习——通过XPath定位元素


    用Xpath定位元素的方法总是记不住,经常要翻出各种文档链接参考,干脆把需要用到的内容整到这个笔记中方便查找。

    Xpath是在XML文档中定位节点的语言。使用 XPath 的主要原因之一是当想要查找的元素缺少合适的 id 或name属性。XPath定位器可以用来绝对或相对定位缺少id或name属性的元素,也可以是用其他属性进行定位。

    通过XPath定位的元素容易受html调整的影响,可以先通过id或name属性找到就近的元素,如父元素,用以加强测试脚本的稳定性。
     
    例如,源文件如下:
    <html>
     <body>
      <form id="loginForm">
       <input name="username" type="text" />
       <input name="password" type="password" />
       <input name="continue" type="submit" value="Login" />
       <input name="continue" type="button" value="Clear" />
      </form>
    </body>
    <html>

    form元素可以这样定位:

    1.绝对定位(最容易受HTML语句改变的影响)

    2.HTML中第一个form元素

    3.包含属性为id,值为“loginForm"的form元素  

    login_form = driver.find_element_by_xpath("/html/body/form[1]")
    login_form = driver.find_element_by_xpath("//form[1]")
    login_form = driver.find_element_by_xpath("//form[@id='loginForm']")
    

    username元素可以这样定位:

    1.form元素的input子元素中包含属性为name,值为”username“的元素

    2.包含属性为id,值为“loginForm"的form元素的第一个input子元素

    3.包含属性为name,值为”username“的第一个input元素

    username = driver.find_element_by_xpath("//form[input/@name='username']")
    username = driver.find_element_by_xpath("//form[@id='loginForm']/input[1]")
    username = driver.find_element_by_xpath("//input[@name='username']")
    

    Clear按钮可以这样定位:

    1.同时包含属性为name,值为”continue“和属性为type,值为”button“的input元素

    2.包含属性为id,值为“loginForm"的form元素的第4个input子元素

    clear_button = driver.find_element_by_xpath("//input[@name='continue'][@type='button']")
    clear_button = driver.find_element_by_xpath("//form[@id='loginForm']/input[4]")
    

      

    附Xpath学习链接,参见:http://www.w3school.com.cn/xpath/index.asp

    有助于发现元素的Xpath的附加组件有:

    Xpath Checker (交互式的 XPath 表达式编辑器)

    Firebug (对网页的CSS、HTML和JavaScript进行实时编辑、调试和监控)

    XPath Helper (便于提取、编辑和评估网页的Xpath)

    英文文档出处,参见https://selenium-python.readthedocs.org/en/latest/locating-elements.html

  • 相关阅读:
    数论模板
    HZNU_TI1050 训练实录
    2019 ICPC Asia Xuzhou Regional
    ICPC 2019-2020 North-Western Russia Regional Contest
    2019 ICPC Asia Yinchuan Regional
    2019-2020 ICPC, Asia Jakarta Regional Contest
    The 2019 China Collegiate Programming Contest Harbin Site
    2019-2020 ICPC, NERC, Southern and Volga Russian Regional Contest
    Educational Codeforces Round 75
    2018-2019 ACM-ICPC, Asia Dhaka Regional Contest
  • 原文地址:https://www.cnblogs.com/liutong3310/p/3715851.html
Copyright © 2020-2023  润新知