java,Webdriver, I want to fetch all links in a webpage and then compare them to a string name that I have and if it is found then click it

StackOverflow https://stackoverflow.com/questions/23479694

  •  16-07-2023
  •  | 
  •  

Question

java, Webdriver, So now i have this, but the casting in the third line is giving me errors

public void getLinks(String linkName)throws Exception{

try { 

    List<WebElement> links = ((Webelement)driver).findElements(By.tagName("a")); 

    for (WebElement myElement : links){ 

        String link = myElement.getText();

        if (link.equals(linkName)){
         myElement.click();
         } 

    } 
 }catch (Exception e){

    System.out.println("Error the link was not found "+e); 

} }

and if i run it this is what i see: Starting ChromeDriver (v2.6.232923) on port 34733 Error the link was not found java.lang.ClassCastException: java.lang.ThreadLocal cannot be cast to org.openqa.selenium.WebElement PASSED: testing

Also my second idea is that it is not finding: “tagName("a"));” for links. But then when I go to the web I see Contacts in Portugal covering Airlines So the links are in “a” tags, so I don’t think is this. And im passing this : String linkName= "Contacts in Portugal covering Airlines";

Was it helpful?

Solution

I think this is a wrong assertion:

if (assertEquals(linkName, myElement)){
    myElement.click();
} 

.. because linkName is a String, myElement is a WebElement and the assertEquals() return value is not boolean (only void). You can check it with String equals(). For example:

if (link.equals(linkName)){
    myElement.click();
} 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top