八大元素定位

发布时间 2023-07-07 23:00:29作者: vorn

一、八种元素定位的方法:

id,name,class类名,tag_name标签名,link_text链接文本,partail_link_text部分链接文本,xpath,css

xpath

绝对路径:使用/

/html/body/div/div/div......    #实际工作中不会使用

相对路径:使用//

  1.相对路径://form/span/input  #定位所有form标签下有span标签下有input标签的元素

  2.相对路径+索引定位://form/span[1]/input  #定位form标签下第1个span标签下的input标签下的元素

  3.相对路径+属性定位://input[@autocomplete='off']  #定位带有autocomplete='off'属性的input标签下的元素

  4.相对路径+属性组合:

  and://input[@name='wd' and @autocomplete='off']

  or://input[@name='wd' or @autocomplete='off']

  5.相对路径+通配符*://*[@*='wd' or @*='off']  #标签名、属性名可以用通配符代替

  6.以上所有的方式都可以组合使用://form[@*='form' and @name='f']/span[1]/input

#演示:

from selenium import webdriver
from selenium.webdriver.common.by import By
import time

url="https://www.baidu.com/"

driver=webdriver.Chrome()  #打开浏览器
driver.implicitly_wait(10)  #隐性等待10秒
driver.get(url)  #访问url
# driver.find_element(By.XPATH,"//form/span/input").send_keys("相对路径")
# driver.find_element(By.XPATH,"//form/span[1]/input").send_keys("相对路径+索引定位")
# driver.find_element(By.XPATH,"//input[@autocomplete='off']").send_keys("相对路径+属性定位")
# driver.find_element(By.XPATH,"//input[@name='wd' and @autocomplete='off']").send_keys("相对路径+属性组合")
# driver.find_element(By.XPATH,"//input[@name='wd' or @autocomplete='off']").send_keys("相对路径+属性组合")
# driver.find_element(By.XPATH,"//*[@*='wd' or @*='off']").send_keys("相对路径+通配符*")
driver.find_element(By.XPATH,"//form[@*='form' and @name='f']/span[1]/input").send_keys("相对路径+组合使用")

time.sleep(5)

动态元素定位

相对路径+部分属性值定位:

属性值以of开头://input[starts-with(@autocomplete,'of')]  #匹配以of开头

属性值以ff结尾://input[substring(@autocomplete,2)='ff']  #匹配第2位到最后一位

属性值中间包含f://input[contains(@autocomplete,'f')]  #匹配带有'f'的

#演示:

driver.find_element(By.XPATH,"//input[starts-with(@autocomplete,'of')]").send_keys("相对路径+部分属性值定位")
driver.find_element(By.XPATH,"//input[substring(@autocomplete,2)='ff']").send_keys("相对路径+部分属性值定位")
driver.find_element(By.XPATH,"//input[contains(@autocomplete,'f')]").send_keys("相对路径+部分属性值定位")

文本定位