Selenium元素定位

提供了8种定位方法:

  • id
  • name
  • class name
  • tag name
  • link text
  • partial link text
  • XPath
  • CSS Selector

对应的方法:

  • findElement(By.id())
  • findElement(By.name())
  • findElement(By.className())
  • findElement(By.tagName())
  • findElement(By.linkText())
  • findElement(By.partialLinkText())
  • findElement(By.xpath())
  • findElement(By.cssSelector())

定位方法的用法

<html>
  <head>
  <body link="#0000cc">
    <a id="result_logo" href="/" onmousedown="return c({'fm':'tab','tab':'logo'})">
    <form id="form" class="fm" name="f" action="/s">
      <span class="soutu-btn"></span>
        <input id="kw" class="s_ipt" name="wd" value="" maxlength="255" autocomplete="off">
  • driver.findElement(By.id("kw"))
  • driver.findElement(By.name("wd"))
  • driver.findElement(By.className("s_ipt"))
  • driver.findElement(By.tagName("input"))
  • XPATH写法
driver.findElement(By.xpath("//*[@id='kw']"))
driver.findElement(By.xpath("//*[@name='wd']"))
driver.findElement(By.xpath("//input[@class='s_ipt']"))
driver.findElement(By.xpath("/html/body/form/span/input"))
driver.findElement(By.xpath("//span[@class='soutu-btn']/input"))
driver.findElement(By.xpath("//form[@id='form']/span/input"))
driver.findElement(By.xpath("//input[@id='kw' and @name='wd']"))
//label[text()='{0}']/parent::div/following-sibling::div//i[contains(@class, 'canzhao')]

//span[contains(@class, 'expand-icon')]
 
  • CSS写法
driver.findElement(By.cssSelector("#kw")
driver.findElement(By.cssSelector("[name=wd]")
driver.findElement(By.cssSelector(".s_ipt")
driver.findElement(By.cssSelector("html > body > form > span > input")
driver.findElement(By.cssSelector("span.soutu-btn> input#kw")
driver.findElement(By.cssSelector("form#form > span > input")

css写法参考:https://www.w3school.com.cn/cssref/css_selectors.asp

 

posted @ 2021-04-29 20:48  keep2021  阅读(57)  评论(0编辑  收藏  举报