简体   繁体   English

如何在selenium webdriver中从网页中提取所有链接后单击特定链接

[英]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 .我是自动化世界的新手,致力于自动化 BBC 网站。 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):您可以使用 Xpath 直接单击具有特定文本内容的链接,如下所示(未经测试的代码):

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.一般来说,如果可能的话,最好用 id 或唯一的 CSS 选择器来标识元素。

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.您还可以遍历您手动拥有的 Web 元素列表并检查其中的文本(通过getText() 之类的方法)并单击自己。

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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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