簡體   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