python_selenium元素定位_xpath(2)
selenium自动化脚本最基础的就是元素定位和元素操作,下面就以百度为例介绍最常见的xpath定位方式
基本定位方式:
以百度的搜索框为例
from selenium import webdriver
import time
driver = webdriver.Chrome()
driver.get("https://www.baidu.com")
driver.maximize_window()
time.sleep(2)
# 1、绝对路径
# driver.find_element_by_xpath("/html/body/div/div/div/div/div/form/span/input").send_keys("龙猫")
# 2、相对路径
# driver.find_element_by_xpath("//form/span/input").send_keys("龙猫")
# 3、通过元素索引定位
# driver.find_element_by_xpath("//div/div[3]/a[3]").click()
# 4、使用元素属性定位
# 4.1 单属性
# driver.find_element_by_xpath("//input[@maxlength = ‘255‘]").send_keys("小狗")
# 4.2 多属性and
# driver.find_element_by_xpath("//input[@maxlength=‘255‘ and @autocomplete=‘off‘]").send_keys("小狗")
# 4.3 多属性or
# driver.find_element_by_xpath("//input[@maxlength=‘259‘ or @autocomplete=‘off‘]").send_keys("小狗")
# 5、模糊匹配
# 5.1 以什么开头starts-with()
# driver.find_element_by_xpath("//a[starts-with(@name,‘tj_trn‘)]").click()
# 5.2 以什么结尾substring()
# driver.find_element_by_xpath("//a[substring(@name,6)=‘news‘]").click()
# 5.3 包含contains()
# driver.find_element_by_xpath("//a[contains(@name,‘trne‘)]").click()
# 6、使用元素文本定位text()函数
# driver.find_element_by_xpath("//a[text()=‘新闻‘]").click()
driver.find_element_by_xpath("//a[contains(text(),‘新‘)]").click()这些就是xpath定位最常用的,至于怎么选择使用就看自己具体的使用情况了。
相关推荐
paleyellow 2020-10-25
baifanwudi 2020-10-25
LxyPython 2020-08-17
fangjack 2020-06-25
云之高水之远 2020-06-20
maowenbei 2020-06-10
tiankele0 2020-06-09
Andrewjdw 2020-05-29
zengni 2020-05-29
Alanxz 2020-05-28
yogoma 2020-05-28
freerocker 2020-05-26
andrewwf 2020-05-08
我欲疾风前行 2020-04-30
坚持是一种品质 2020-04-25
sunzhihaofuture 2020-03-27
RuoShangM 2020-03-23