简体   繁体   中英

How to click on specific link after extracting all the links from a web page in selenium webdriver

I am new to automation world and working on automating the BBC website . I have got number of links and also the text present in that links. . I want to click on a particular link with text "Accessibility Help". please advise how can i do it. following is my code:

  import java.util.List;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;


public class BBC_AllLinks {

    public static void main(String[] args) throws InterruptedException {
        // TODO Auto-generated method stub

        WebDriver driver = new FirefoxDriver();
        driver.get("http://www.bbc.com");
        List<WebElement> allLinks = driver.findElements(By.tagName("a"));
        //Total number of links in the webpage
        System.out.println("Total Links--> "+allLinks.size());
        //35th index
        Thread.sleep(4000);
    for (int i =0; i<=allLinks.size();i++)
        System.out.println(allLinks.get(i).getText()+"----"+allLinks.get(i).isDisplayed());
    }

}

You can directly click the link with a specific text content using Xpath, something like this (untested code):

driver.findElement(By.xpath("//a[contains(text(), \"Accessibility Help\")]")).click();

Note that if there are multiple links with this text, it will try to click on the first one that satisfies the condition going in document order. Generally it is better to identify elements with something like id or a unique CSS selector if possible.

You could also loop over the list of web elements you have manually and check for the text inside (by something like getText() ) and click yourself.

I'm confused about what your code is supposed to be doing. Are you trying to log all links on the page and then click on the link? Or are you just trying to click on the link?

If all you are trying to do is click on that one link then this is all you need.

driver.findElement(By.linkText("Accessibility Help")).click();

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