Home > Enterprise >  Keep scrolling a section until parent tag attribute is "disabled" in Selenium WebDriver
Keep scrolling a section until parent tag attribute is "disabled" in Selenium WebDriver

Time:11-23

I have an application with a few sections with pics and each section has a scroll link to scroll right

<div >
  <i >

the div class attribute changes to "owl-next-disabled" when u can't scroll anymore. I want to be able to scroll to the last picture in each section. i have been able to come up with code below with one 'for' loop to loop through the div webelements but within the loop i am able to click only once before element not found exception in thrown because owl-next disabled' is not found.

List<WebElement> divtag=driver.findElements(By.xpath("//div[@class='owl-next']"));
    Thread.sleep(1000);
    int i=1;
    if(divtag!=null)
    {
       for(WebElement clickright:divtag)
            {
                
                WebElement rightscroll=driver.findElement(By.xpath("//div/i[@class='fa fa-angle-right']"));
                rightscroll.click();
                WebElement ele=driver.findElement(By.xpath("//div/i[@class='owl-next disabled']"))!=null)
                        
            }
                            
        }   
    }
                    

how do i scroll through till the attribute of the div tag is 'owl-next disabled'?

CodePudding user response:

The problem is this:

  1. You click() to scroll to the right.
  2. You try to find 'owl-next disabled', but that is absent because you need to scroll more

What you want is to check if an element exists, if not continue clicking to go right. findElement() MUST find an element or it throws an error, findElements() gives a list which might be empty.

for(WebElement clickright : divtag)
{   
    while(true){        
        WebElement rightscroll=driver.findElement(By.xpath("//div/i[@class='fa fa-angle-right']"));
        rightscroll.click();
        List<WebElement> endList = driver.findElement(By.xpath("//div/i[@class='owl-next disabled']"))!=null);
        if(endList.Count() == 0)
            break;
    }
}

Add a 'safety' which stops after 100 right clicks if necessary

CodePudding user response:

while(true)
{
    WebElement parent = clickright.findElement(By.xpath("./.."));
    if(parent.getAttribute("class").equalsIgnoreCase("owl-next disabled"))
        break;
    System.out.println(clickright.getAttribute("class"));       
    clickright.click();                         
}

Retrieved the parent tag and compared with disabled text, now its working.

  • Related