3. 定位单个对象

以下方法都可以用来定位某个对象,优先选择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

  1. Location by ID
    login_form = driver.find_element_by_id('loginForm')
  2. Location by Name
    username = driver.find_element_by_name('username')
    password = driver.find_element_by_name('password')

  3. 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和type
    clear_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]")

     

    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

  4. Location Hyperlink by Link Text
    continue_link = driver.find_element_by_link_text('Continue')
    continue_link = driver.find_element_by_partial_link_text('Conti')
  5. Location by Tag Name
    heading1 = driver.find_element_by_tag_name('h1')
  6. Location by Class Name
    content = driver.find_element_by_class_name('content')
    
    
  7. Location by CSS Selector
    content = driver.find_element_by_css_selector('p.content')

    Sauce Labs has good documentation on CSS selectors.
posted @ 2014-07-18 14:47  hugh007  阅读(248)  评论(0)    收藏  举报