以下方法都可以用来定位某个对象,优先选择id,name.
- 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
- Location by ID
login_form = driver.find_element_by_id(‘loginForm‘)
- Location by Name
username = driver.find_element_by_name(‘username‘) password = driver.find_element_by_name(‘password‘)
- Location by XPATH
绝对路径(如何html有轻微的调整就会失效)login_form = driver.find_element_by_xpath("/html/body/form[1]")相对路径元素位置 login_form = driver.find_element_by_xpath("//form[1]")相对路径元素属性 login_form = driver.find_element_by_xpath("//form[@id=‘loginForm‘]") 相对路径子元素的name属性username = driver.find_element_by_xpath("//form[input/@name=‘username‘]")相对路径id熟悉后index username = driver.find_element_by_xpath("//form[@id=‘loginForm‘]/input[1]")相对路径name属性 username = driver.find_element_by_xpath("//input[@name=‘username‘]") 相对路径中的双属性name和typeclear_button = driver.find_element_by_xpath("//input[@name=‘continue‘][@type=‘button‘]")相对路径中前id属性后index clear_button = driver.find_element_by_xpath("//form[@id=‘loginForm‘]/input[4]")
- W3Schools XPath Tutorial
- W3C XPath Recommendation
- XPath Tutorial - with interactive examples.
There are also a couple of very useful Add-ons that can assist in discovering the XPath of an element:
- XPath Checker - suggests XPath and can be used to test XPath results.
- Firebug - XPath suggestions are just one of the many powerful features of this very useful add-on.
- XPath Helper - for Google Chrome
- Location Hyperlink by Link Text
continue_link = driver.find_element_by_link_text(‘Continue‘) continue_link = driver.find_element_by_partial_link_text(‘Conti‘)
- Location by Tag Name
heading1 = driver.find_element_by_tag_name(‘h1‘)
- Location by Class Name
content = driver.find_element_by_class_name(‘content‘)
- Location by CSS Selector
content = driver.find_element_by_css_selector(‘p.content‘)
Sauce Labs has good documentation on CSS selectors.
3. 定位单个对象
时间: 2024-08-26 08:49:16