python css和xpath_Selenium系列教程(四)css、xpath定位(基于 Python)

#!/usr/bin/env python

importtimefrom selenium importwebdriver

driver=webdriver.Chrome()

driver.get("http://localhost:63342/webtest/demo.html")#节点

driver.find_element_by_xpath("/html/body/div") #绝对路径,从根节点开始,一旦页面改变必须重新定位,不推荐

driver.find_elements_by_xpath("//div//a") #相对路径,从当前节点开始而不考虑它们的位置:选取div下面的a元素

driver.find_element_by_xpath("//input/..") #选择 input 元素的父节点

driver.find_element_by_xpath("//*") #选择所有节点

#谓语:谓语是用来查找某个特定的节点或者包含某个指定的值的节点,谓语被嵌在方括号[]中。#索引

driver.find_element_by_xpath("//a[1]") #索引,选择第一个 a 元素#属性选择器 @

driver.find_element_by_xpath("//span[@class='name']/input") #选择 class=name 的span元素下的input元素

driver.find_element_by_xpath("//input[@type]") #选取所有含有 type 属性的 input 元素

driver.find_element_by_xpath("//input[@*]") #选取所有带有属性的 input 元素#运算符、函数

driver.find_element_by_xpath("//*[@name='pwd' and @class='s-wd']") #逻辑运算 and、or、not

driver.find_element_by_xpath("//book/title | //book/price") #book下的title 和book 下的price

driver.find_element_by_xpath("//div/input[last()]") #属于div的最后一个 input

driver.find_element_by_xpath("//div/input[last()-1]") #属于div的倒数第二个input

driver.find_element_by_xpath("//div/input[position()<2]") #选择属于div的最前面的input元素

driver.find_element_by_xpath("//book[price>30]") #price>30的book元素

#模糊匹配

ele = driver.find_element_by_xpath("//*[contains(@class, 'wd')]")print(ele.get_attribute("id"))

driver.find_element_by_xpath("//*[starts-with(@id, 'p')]")#文本定位

driver.find_element_by_xpath("//a[text()='百度']")"//a/text()" #获取a标签的所有文本

#轴#子元素 child

driver.find_element_by_xpath("//div[contains(@class,'account')]//child::*") #class包含account的div下的所有子元素(不知道为什么也查出了后代元素???)

driver.find_element_by_xpath("//div[contains(@class,'account')]//child::input[@id='kw']")#先辈 ancestor

driver.find_element_by_xpath("//input[@id='test']//ancestor::div")#先辈和自己 ancestor-or-self

driver.find_element_by_xpath("//input[@id='test']//ancestor-or-self::*")#parent:父辈

driver.find_element_by_xpath("//input[@id='test']//parent::*")#descendant 后代子孙

driver.find_element_by_xpath("//div[contains(@class,'account')]//descendant::*")#descendant-or-self 后代及自己

driver.find_element_by_xpath("//div[contains(@class,'account')]//descendant-or-self::*")#当前节点之后的所有节点 following

driver.find_element_by_xpath("//input[@id='pwd']/following::*")#当前节点之前的所有节点 preceding

driver.find_element_by_xpath("//input[@id='pwd']/preceding::*")#attribute 选取当前节点的所有属性。

"//input[@id='pwd']/attribute::*"

#哥哥姐姐(当前节点之前的同级节点)preceding-sibling

driver.find_element_by_xpath("//input[@id='pwd']/preceding-sibling::*")

time.sleep(1)

driver.quit()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值