Selenium 常见控件定位方法

139 阅读1分钟

  文章转载链接www.51testing.com/html/29/n-7…

  HTML知识铺垫

  <html>
  <head>
  <meta charset="utf-8">
  <title>测试人论坛</title>
  </head>
  <body>
  <a href="https://ceshiren.com/" class="link">链接</a>
  </body>
  </html>

  · 标签:< a >

  · 属性:href

  · 类属性: class

  Selenium定位方式

1.png

  Selenium常用定位方式

  driver.find_element_by_定位方式(定位元素)
  driver.find_element(By.定位方式, 定位元素) 
  # 示例,两种方式作用一模一样
  # 官方建议使用下面的方式
  driver.find_element_by_id("su")
  driver.find_element(By.ID, "su") 

  实战:

  def open_browser():
      driver = webdriver.Chrome()
      driver.get('https://vip.ceshiren.com/#/ui_study')
      #id定位
      id_item = driver.find_element(By.ID,"locate_id")
      print(id_item)
      #name定位
      name_item = driver.find_element(By.NAME,"locate")
      print(name_item)
      # CSS选择器定位
      css_item = driver.find_element(By.CSS_SELECTOR, "#locate_id")
      print(css_item)
      #xpath定位
      xpath_item = driver.find_element(By.XPATH,'//*[@id="locate_id"]')
      print(xpath_item)
      #通过链接文本的方式:元素一定是a标签,输入的元素为标签内的文本
      link_text = driver.find_element(By.LINK_TEXT,"元素定位")
      print(link_text)
      time.sleep(2)