一、Xpath高级用法基础格式
- 格式
/轴方法::标签名[标签属性] - 实例
//div/parent::span[@name=‘interName’] - 实例解释:
定位span标签,span标签是div标签的父级,且span标签的name属性值为:interlNmae
二、基础格式详解
2.1层级路径格式
- 讲解
![059d7ac588f7a97ccf6842473deaea34.png](https://img-blog.csdnimg.cn/img_convert/059d7ac588f7a97ccf6842473deaea34.png)
- 实例
![46b5056a4c4ef7a3e3592de5850b00d0.png](https://img-blog.csdnimg.cn/img_convert/46b5056a4c4ef7a3e3592de5850b00d0.png)
2.2标签位置以及标签属性
- 讲解
![4c7b5080b0e6c390c00db8c147876ee6.png](https://img-blog.csdnimg.cn/img_convert/4c7b5080b0e6c390c00db8c147876ee6.png)
- 实例
![4aadea2449de6d32abb8c67773222669.png](https://img-blog.csdnimg.cn/img_convert/4aadea2449de6d32abb8c67773222669.png)
2.3 xpath轴方法
- 讲解
![210d624947f3fd5c6f988baa2911ed16.png](https://img-blog.csdnimg.cn/img_convert/210d624947f3fd5c6f988baa2911ed16.png)
- 实例
![a0a5f6c21b31a636bdc775bb632e64f1.png](https://img-blog.csdnimg.cn/img_convert/a0a5f6c21b31a636bdc775bb632e64f1.png)
2.4常用运算符
![dc3778d424bab99e0622e688eb77411f.png](https://img-blog.csdnimg.cn/img_convert/dc3778d424bab99e0622e688eb77411f.png)
三、实例演示
- 常见场景:输入框定位有时候经常遇到输入框表单很多,也没有唯一标识id等,chrome复制的xpath非常的长,而且容易失效,但是如果根据输入框前的字段名称来作为标识,那定位就比较稳定了。这里我来演示的是百度的注册页面,这里输入框的输入通过字段名称来作为唯一标识,来定位输入框
xpath = //label[text()=‘用户名’]/following-sibling::input[last()]
![591f6f8fe41321707ec659ea71a7597a.png](https://img-blog.csdnimg.cn/img_convert/591f6f8fe41321707ec659ea71a7597a.png)
代码:from selenium import webdriverdriver = webdriver.Chrome()driver.implicitly_wait(10)driver.set_page_load_timeout(15)driver.get("https://passport.baidu.com/v2/?login")# 点击注册driver.find_element("xpath", "//a[text()='立即注册']").click()# 切换页签all_handle = driver.window_handlesdriver.switch_to.window(all_handle[1])# 定位标签driver.find_element("xpath", "//label[text()='用户名']/following-sibling::input[last()]").send_keys("川石学院")driver.find_element("xpath", "//label[text()='手机号']/following-sibling::input[last()]").send_keys("13691729932")driver.find_element("xpath", "//label[text()='密码']/following-sibling::input[last()]").send_ke