4-selenium-xpath定位

from selenium import webdriver

"""
xpath 定位:
xpath路径:绝对路径  /    例子:/html/body/form/input
          相对路径  //    例子: //input  所有input元素   尽量使用相对路径简短
通配符:  //form/*    所有form路径下的所有元素
列表选择索引从1开始: //td[1]/a[last()]
选择属性: "//input[@name='kw']" ; "//input[@name='kw' and @class='kw']"
常用函数:contains()  //a[contains(@href,'新闻')]
         text()   //a[text()='新闻']    ; //a[contains(text(),'新闻')]
xpath轴:这些方法都不能定位时,这时候就得考虑依据元素的父辈、兄弟或者子辈节点来定位了。轴名称::标签名
        //input[@class='kw']/parent::div   当前节点父节点是div   --->找的是上一级的元素
        //a[contains(text(),'新闻')]/child::div   当前a元素的子元素div   ---->找的是下一级元素
        //input[@class='kw']/ancestor::div  当前input元素的所有先辈们(父亲、爷爷)  --->找的是上级或者上上级的元素
        //input[@class='kw']/descendant::a  当前input元素中有的子代、子子代a元素    --->找的是下一级、或者下下一级的元素
"""

from selenium import webdriver

driver = webdriver.Chrome()
driver.get('http://wwww.baidu.com')
'''<input id="kw" name="wd" class="s_ipt" value="" maxlength="255" autocomplete="off">通过浏览器copy 元素'''
# driver.find_element_by_xpath("//*[@name='wd']").send_keys('Hello')   # *通配符代表任何一个元素   通过属性:id、name、class获取元素
# driver.find_element_by_xpath("//input[@id='kw']").send_keys('hello')
'''
<div id="u1">
    <a href="https://voice.baidu.com/act/newpneumonia/newpneumonia/?from=osari_pc_1" target="_blank" id="virus-2020" class="mnav sp dot">抗击肺炎</a>
    <a href="http://news.baidu.com" name="tj_trnews" class="mnav">新闻</a><a href="https://www.hao123.com" name="tj_trhao123" class="mnav">hao123</a>
    <a href="http://map.baidu.com" name="tj_trmap" class="mnav">地图</a><a href="http://v.baidu.com" name="tj_trvideo" class="mnav">视频</a>
    <a href="http://tieba.baidu.com" name="tj_trtieba" class="mnav">贴吧</a><a href="http://xueshu.baidu.com" name="tj_trxueshu" class="mnav">学术</a>
    <a href="https://passport.baidu.com/v2/?login&amp;tpl=mn&amp;u=http%3A%2F%2Fwww.baidu.com%2F&amp;sms=5" name="tj_login" class="lb" onclick="return false;">登录</a>
    <a href="http://www.baidu.com/gaoji/preferences.html" name="tj_settingicon" class="pf">设置</a><a href="http://www.baidu.com/more/" name="tj_briicon" class="bri" style="display: block;">更多产品</a>
</div>
'''
# driver.find_element_by_xpath("//*[@id='u1']/a[1]").click()   # 索引获取元素。链接可以通过click()方法点击
# driver.find_element_by_xpath("//div[@id='u1']/a[last()]").click()   # last()函数代表最后一个
# driver.find_element_by_xpath("//a[contains(text(),'新闻')]/parent::div")  # 定位到这个没有操作
原文地址:https://www.cnblogs.com/tarzen213/p/12462558.html