繁体   English   中英

了解硒中的方法findElement

[英]Understanding the Method findElement in Selenium

我试图理解不同的接口,在Selenium中实现接口和方法的类。

我可以理解,接口SearchContext是由接口WebDriver继承的,而该接口又由不同的类(如ForefoxDriver和其他类)实现。

findElement是SearchContext接口的一种方法,由FirefoxDriver实现(因为fireFoxDriver实现了WebDriver)。

还有另一个名为“按”的类,它具有一组嵌套的子类。

现在,findElement的语法如下:

driver.findElement(By.name("q"));

我无法理解传递给方法findElement的参数,因为它是作为参数传递的对象,还是在findElement方法内部调用了其他函数?

任何人都可以澄清传递给此函数findElement的参数的确切含义吗?

谢谢。

(Java)根据Selenium 2 API,

#findElement():

  Find the first WebElement using the given method. This method is affected by the 'implicit wait' times in force at the time of execution. The findElement(..) invocation will return a matching row, or try again repeatedly until the configured timeout is reached. findElement should not be used to look for non-present elements, use findElements(By) and assert zero length response instead.
  Specified by: findElement(...) in SearchContext

  Parameters:
    by The locating mechanism

  Returns:
    The first matching element on the current page

  Throws:
    NoSuchElementException - If no matching elements are found

  See Also:
    org.openqa.selenium.By
    org.openqa.selenium.WebDriver.Timeouts

findElement()有一个参数。 By类的对象。 让我们看一下By类。

By.className       : Finds elements based on the value of the "class" attribute.
By.cssSelector     : Finds elements via the driver's underlying W3 Selector engine.
By.id              : a By which locates elements by the value of the "id" attribute.
By.linkText        : a By which locates A elements by the exact text it displays
By.name            : a By which locates elements by the value of the "name" attribute.
By.partialLinkText : a By which locates A elements that contain the given link text
By.tagName         : a By which locates elements by their tag name
By.xpath           : a By which locates elements via XPath

简而言之,这些都是找到所需要素的所有方法。 这完全取决于您选择的哲学。 我个人总是使用By.cssSelector

这是硒选择元素的方式,类似于流利的api。 它使用户更容易阅读。 传递给findElement的参数有点像伪选择器查询,类似于Jsoup。

例如,如果您想选择此页面左上角的SO徽标,则可以

driver.findElement(By.id("hlogo"));

因此,查询By.name("q")基本上会选择属性为name="q"元素

在解析DOM对象时,您可以使用多种方式获取元素

  • 您可以通过id获取元素
  • 您可以通过其名称获取元素
  • 您可以按其类获取元素

因此有多种获取元素的方法

在硒中,当您使用findElement方法时,您将不得不说“正在使用哪个”来指示硒查找元素? 使用名称或ID或watever,它是..

这就是为什么他们给了By类。 因此,如果要查找具有类名的元素,则可以使用findElement(By.ByClassName)

如果要通过ID查找元素,则可以使用findElement(By.ById)

看到这个API链接

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM