# BY.ID
driver = webdriver.Chrome()
driver.get("https://www.baidu.com/")
driver.find_element(By.ID, "kw").send_keys("自动化")
# BY.NAME
driver.find_element(By.NAME, "wd").send_keys("自动化")
# BY.LINK_TEXT,链接文本
driver.find_element(By.LINK_TEXT, "新闻").click()
# BY.PARTIAL_LINK_TEXT,部分文本链接
driver.find_element(By.PARTIAL_LINK_TEXT, "新").click()
# BY.XPATH定位,分为五种
# 相对路径+索引定位
# 定位form模块第一个span标签下的input
driver.find_element(By.XPATH, "//form/span[1]/input")
# 相对路径+属性定位
driver.find_element(By.XPATH, "//[@autocomplete = 'off']")
# 相对路径+通配符定位,*是通配符,匹配所有属性值为off的属性
driver.find_element(By.XPATH, "//*[@* = 'off']")
driver.find_element(By.XPATH, "//*[@autocomplete = 'off']")
# 相对路径+部分属性值定位,属性要唯一
driver.find_element(By.XPATH, "//*[starts-with(@autocomplete.'ff')]")
driver.find_element(By.XPATH, "//*[substring(@autocomplete,2) = 'ff']")
driver.find_element(By.XPATH, "//*[contains(@autocomplete ,'ff')]")
# 相对路径+文本标签值定位
driver.find_element(By.XPATH, "//span[text() = '按图片搜索']")
# 组合定位
# 标签名#id属性值:指的是该input标签下id属性为kw的元素
driver.find_element_by_css_selector("input#kw")
# 标签名.class属性值:指的是该input标签下class属性为s_ipt的元素
driver.find_element_by_css_selector("input.s_ipt")
# 标签名[属性=’属性值‘]:指的是该input标签下name属性为wd的元素
driver.find_element_by_css_selector('input[name="wd"]')
# 父级元素标签名>标签名.class属性值:指的是span下的input标签下class属性为s_ipt的元素
driver.find_element_by_css_selector("span>input.s_ipt")
# 多个属性组合定位元素(常用)
# 指的是input标签下id属性为kw且name属性为wd的元素
driver.find_element_by_css_selector('input.s_ipt[name="wd”]')
# 指的是input标签下name属性为wd且maxlength为100的元素
driver.find_element_by_css_selector('input[name="wd"][maxlength="100"]')
WEB-UI自动化测试-最全元素定位方法
于 2022-07-01 09:17:35 首次发布