selenium webdriver python 元素定位

总结

 
定位查找时,返回查找到的第一个match的元素。如果找不到,则 raise NoSuchElementException
 
单个元素定位:

find_element_by_id
find_element_by_name
find_element_by_xpath
find_element_by_link_text
find_element_by_partial_link_text
find_element_by_tag_name
find_element_by_class_name
find_element_by_css_selector

多个元素定位:

find_elements_by_name
find_elements_by_xpath
find_elements_by_link_text
find_elements_by_partial_link_text
find_elements_by_tag_name
find_elements_by_class_name
find_elements_by_css_selector

其他定位方法(属于Page Object的private方法):

from selenium.webdriver.common.by import By

driver.find_element(By.XPATH, '//button[text()="Some text"]')
driver.find_elements(By.XPATH, '//button')

其中,By可以是:

ID = "id"
XPATH = "xpath"
LINK_TEXT = "link text"
PARTIAL_LINK_TEXT = "partial link text"
NAME = "name"
TAG_NAME = "tag name"
CLASS_NAME = "class name"
CSS_SELECTOR = "css selector"

具体

1. id

driver.find_element_by_id(‘userid’)

 

2. name

driver.find_element_by_name(‘username’)

 

3. tagName

driver.find_element_by_tag_name(“input”)

 

4. class Name

driver.find_element_by_class_name(“nv”)

 

5. link text 

driver.find_element_by_link_text(“关于百度”)

 

6. partial link text

driver.find_element_by_partial_link_text(“关于”)

 

7.CSS selector

driver.find_element_by_css_selector(“a[name=\”tj_news\”]”)
 
8. xpath
driver.find_element_by_xpath(“//input[@id=‘kw’]”)
 
9. 层级定位

menu = driver.find_element_by_id('dropdown1').find_element_by_link_text('Action')

 

10. 定位一组元素

inputs=driver.find_elements_by_tag_name(‘input’)

 

11. 定位最后一个元素

driver.find_elements_by_css_selector(‘input[type=checkbox]’).pop().click
posted @ 2015-11-20 13:17  微微微笑  阅读(561)  评论(0编辑  收藏  举报