selenium3+python自动化-xpath学习总结

一、环境

  浏览器:Chrome  77.0.3865.75

  selenium版本:cmd 中执行pip show selenium命令 显示3.141.0

二、xpath总结

  1.xpath+id/name/class定位:

  driver.find_element_by_xpath('//标签名[@id="id值"]')

  driver.find_element_by_xpath('//标签名[@name="name值"]')

  driver.find_element_by_xpath('//标签名[@class="class值"]')

  若想指定标签,则标签名直接写具体的标签名,若不想指定,则用*代替

  例:

# driver.find_element_by_xpath('//*[@id="kw"]').send_keys('python')#*代替任意标签
# driver.find_element_by_xpath('//input[@id="kw"]').send_keys('python')#具体标签

  2.xpath+其他属性定位:

  driver.find_element_by_xpath('//标签名[@属性名="属性值"]')

  3.xapth层级定位

  如果xpath无法直接定位,则可以先找到它的爸爸或者爷爷,再一层一层定位

   用它爸爸定位,报错了

#定位他的老爸来定位input输入框,结果错误
# driver.find_element_by_xpath('//span[@class="bg s_ipt_wr quickdelete-wrap"]/input').send_keys('python')
#定位他的爷爷来定位input输入框
# driver.find_element_by_xpath('//*[@id="form"]/span/input').send_keys('python')

  4.xpath索引,xpath的标签相同,兄弟元素的定位,采用索引,此处的索引从1开始计算,与python不同

#xpath索引,兄弟标签的定位,索引是从1开始计算,跟python的索引不同
text1=driver.find_element_by_xpath('//ul[@class="custom_dot  para-list list-paddingleft-1"]/li[1]/div').text
text2=driver.find_element_by_xpath('//ul[@class="custom_dot  para-list list-paddingleft-1"]/li[2]/div').text
text3=driver.find_element_by_xpath('//ul[@class="custom_dot  para-list list-paddingleft-1"]/li[3]/div').text
print(text1,text2,text3)

  5.xpath 逻辑计算 and/or/not,多个属性进行查找

  driver.find_element_by_xpath('//标签名[@属性1=“属性值1” and @属性2=“属性值2”]')

#xpath多属性
text=driver.find_element_by_xpath('//div[@class="para" and @label-module="para"]')
print(text)

   6.xpath模糊匹配,contains()用的多

  driver.find_element_by_xpath('//标签名[contains(text(),"要匹配的值")]')

  driver.find_element_by_xpath('//标签名[contains(@属性名,"要匹配的值")]')

  driver.find_element_by_xpath('//标签名[starts-with(@属性名,"要匹配的值")]')

#driver.find_element_by_xpath('//*[contains(text(),"hao123")]').click()
#xpath也可以模糊匹配某个属性
#driver.find_element_by_xpath('//*[contains(@id,"kw")]').send_keys('yangxuan')
#xpath可以模糊匹配以什么开头
driver.find_element_by_xpath('//*[starts-with(@id,"kw")]').send_keys('yx')

参考博客:https://www.cnblogs.com/yoyoketang/p/6123938.html

猜你喜欢

转载自www.cnblogs.com/xiaobeibi/p/12188039.html