selenium通过xpath定位

Posted on 2020-03-19 10:26  橙子j  阅读(220)  评论(0)    收藏  举报

还是以百度为例:

<body link="#0000cc" style="">
    <script>...</script>
    <div id="wrapper" style="display: block;">
        <script>...</script>
        <div id="head" class="">
            <div class="head_wrapper">
                <div class="s_form">
                    <div class="s_form_wrapper soutu-env-nomac soutu-env-index">
                        <style>...</style>
                        <div>
                        <a>
                        <form id="form" name="f" action="/s" class="fm">
                            <input>[7]
                            <span class="bg s_ipt_wr quickdelete-wrap ipthover">
                                <span class="soutu-btn"></span>
                                <input id="kw" name="wd" class="s_ipt" value="" maxlength="255" autocomplete="off">
                                <a>
                            </span>
                            <span class="bg s_btn_wr">
                                <input type="submit" id="su" value="百度一下" class="bg s_btn">
                            </span>

 

 

绝对路径:

ele= driver.find_element_by_xpath('/html/body/div/div/div/div/div/form/span/input')
ele=driver.find_element_by_xpath('/html/body/div/div/div/div/div/form/span[2]/input')

span[2]指的是第2个span标签

元素属性

ele= driver.find_element_by_xpath("//input[@id='kw']")

//表示当前页面某个目录下
input表示input标签
[@id='kw']表示id属性值为kw
如果不想指定标签名,也可以用*表示,比如//*[@id="kw"]
xpath任意属性都可以

 

上面两个方法结合(层级和属性结合)

ele=driver.find_element_by_xpath("//form[@class='fm']/span/input")
先定位到span的父元素form,之后向下定位

逻辑运算符

ele=driver.find_element_by_xpath("//form[@class='fm' and @id='form']/span/input")

 

同样可以用生成css的方法,直接生成xpath