Count the number of elements are matching with for the given xpath expression

前端 未结 4 1719
自闭症患者
自闭症患者 2021-02-14 20:35

How to count the number of elements are matching with for the given xpath expression

xpath: driver.findElement(By.xpath(\"//div[contains(@id,\'richedittext_insta         


        
相关标签:
4条回答
  • 2021-02-14 21:08

    Another option If you are basing your requirements strictly on the need to use Selenium, you might be able to do something like this using WebElements and getting the size of the returned list:

    List<WebElement> myListToCheck=currentDriver.findElements(By.xpath("somePath"));
    if(myListToCheck.size()>0){
    //do this
    }else{
    //do something else
    }
    

    Or just simply returning the size of the returned list; if that's all you really want to get from it...

    int mySize=myListToCheck.size()
    

    I believe once you have an established WebElements list, you can also use iterators to go over that list. Helpful, I dunno... just providing another way to get to the same end-game.

    0 讨论(0)
  • 2021-02-14 21:14

    Do the following:

    from selenium.webdriver.common.by import By
    elements = driver.find_elements(By.XPATH, "Your_XPath")
    

    This outputs a list of selenium.webdriver.firefox.webelement.FirefoxWebElements (in my Firefox browser).

    Finally, find out the length of the list:

    len(elements)
    

    NB.: Please note that I have written find_elements() (plural) and NOT find_element(). Both of them are different. find_element() only returns the first matched web element, but to find the list of all the matched web elements, we have to use find_elements().

    0 讨论(0)
  • 2021-02-14 21:16

    Not working in Selenium, which only allows to return nodes from XPath, not primitives like the number returned by count(...). Kept for reference and is valid for most other tools offering a more complete XPath API.

    You should only return least possible amount of data from the query. count(//div[contains(@id,'richedittext_instance')]) counts the number of results within XPath and thus is faster as all the elements do not have to be passed from the XPath engine to Selenium.

    I can't help you with how to fetch this as n int out of selenium, but this should be easy stuff.

    0 讨论(0)
  • 2021-02-14 21:17

    Try this code:

    //Assume driver is intialized properly.
    int iCount = 0;
    iCount = driver.findElements(By.xpath("Xpath Value")).size());
    

    The iCount has the number of elements having the same xpath value.

    0 讨论(0)
提交回复
热议问题