1、ID定位:一般情况下源文档钟没有id
find_element_by_id()
# 定位代码
driver.get(r'https://www.baidu.com/')
element = driver.find_element_by_id('kw')
print(element)
driver.quit()
结果:<selenium.webdriver.remote.webelement.WebElement (session="3e0def3fbbef01b1604038c722b41d35", element="0.08304348633606717-1")>
2、name定位
find_element_by_name()
driver.get(r'https://www.baidu.com/')
element = driver.find_elements_by_name('wd')
print(element)
结果:[<selenium.webdriver.remote.webelement.WebElement (session="46f01fcf2c00a29da78497104ccfed52", element="0.5631928694723543-1")>]
3、class定位
find_element_by_class_name()
driver.get(r'https://www.baidu.com/')
element = driver.find_element_by_class_name('s_ipt')
print(element)
结果:<selenium.webdriver.remote.webelement.WebElement (session="6cded2a9afc8d9e39572c801bf5317eb", element="0.8550768388558103-1")>
示例:定位一组class相同的元素中的第2个
self.find_elements_by_class_name('el-submenu__title')[1]
4、tag定位
driver.get(r'https://www.baidu.com/')
element = driver.find_element_by_tag_name('input').send_keys('selenium')
5、link定位
# 全部文字
driver.get(r'https://www.baidu.com/')
element = driver.find_element_by_link_text('新闻').click()
#部分文字
element = driver.find_element_by_partial_link_text('闻').click()
6、CSS定位
driver.get(r'https://www.baidu.com/')
driver.find_element_by_css_selector('#kw').send_keys('selenium')
7、xpath定位
driver.get(r'https://www.baidu.com/')
driver.find_element_by_xpath("//*[@id='kw']").send_keys('selenium')
网友评论