简体   繁体   中英

FindElement in Selenium without using Xpath

I want do find the element without using xpath, but I have another ul´s elements and "class=title" on my page. So, I cannot use Type or "class=title" either.

<div id="pai">
<div class="def">
    <div class="abc" >
        <p class=title>Title</p>
            <ul>
                <li></li>

I´m thinking about something like below, but I don´t know if it is the best practice:

WebElement um = driver.findElements(By.className("abc"));
WebElement dois = um.findElements(By.className("title"));
tamUl = dois.findElements(By.tagName("ul")).size(); 

In case when you can't or not willing to use Xpath or CSS selectors, you want to get list of all needed elements present on the page. Then you choose (either empirically, by debugging or using conditionals) the index of the specific element to use. Following might be the case you want to try:

List <WebElement> elements = driver.findElements(By.className("title"));

if (elements.size() > 0) {
  elements.get(INDEX_OF_YOUR_ELEMENT).findElements(By.tagName("ul")).size();   
}

Pay attention to the difference between findElement() and findElements() methods. While findElement() returns only first element if multiple occurrences are found, at the same time it throws NoSuchElementException if nothing is found, where findElements() only returns empty list.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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