简体   繁体   English

如何使用Selenium WebDriver来获取所有链接并单击一个链接

[英]How to fetch all links and click those links one by one with Selenium WebDriver

I want to do the following: 我要执行以下操作:

  1. I want to fetch and display all links on webpage. 我想获取并显示网页上的所有链接。
  2. After displaying, I want to click each link one by one. 显示后,我要一个一个地单击每个链接。

I'm able to do point 1 using foreach loop but I'm not able to 2nd point. 我可以使用foreach循环执行第1点,但我无法达到第2点。

Here is the code: 这是代码:

public class OpenAllLinks {
    public static void main(String[] args) {
        WebDriver driver=new FirefoxDriver();
        driver.get("http://bing.com");
        List<WebElement> demovar = driver.findElements(By.tagName("a"));
        System.out.println(demovar.size());

        for (WebElement var : demovar) {
            System.out.println(var.getText()); // used to get text present between the anchor tags
            System.out.println(var.getAttribute("href"));
        }

        for (WebElement var : demovar) {
            var.click();
        }
    }
}

when the first link is clicked, the browser will load the respective page. 当单击第一个链接时,浏览器将加载相应的页面。 hence the other links those you had captured in the first page wouldn't be available. 因此,您在首页中捕获的其他链接将不可用。

If the intent is to navigate to the every link's target, then store the target location and navigate to it, like this 如果要导航到每个链接的目标,请存储目标位置并导航至该位置,如下所示

driver.get("<some site>");
List<WebElement> links=driver.findElements(By.tagName("a"))
ArrayList<String> targets = new ArrayList<String>();
//collect targets locations
for (WebElement link : links) {
     targets.add(link.getAttribute("href"));
}
for (WebElement target : targets) {
     driver.get(target);
     //do what is needed in the target
}

That happens because the link when clicked, navigates to a new page where it doesn't find the next element in your list to click. 发生这种情况的原因是,单击链接时,该链接导航到一个新页面,在该页面中找不到列表中要单击的下一个元素。 Please try the below code that will navigate to each link (I have used the code by @deepak above and have modified it accordingly as per your need) : 请尝试以下将导航到每个链接的代码(我已使用上面@deepak的代码,并根据需要进行了相应的修改)

 WebDriver driver=new FirefoxDriver();

 driver.manage().window().maximize();

 driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

 driver.get("http://bing.com");

 List<WebElement> demovar=driver.findElements(By.tagName("a"));
 System.out.println(demovar.size());

 ArrayList<String> hrefs = new ArrayList<String>(); //List for storing all href values for 'a' tag

    for (WebElement var : demovar) {
        System.out.println(var.getText()); // used to get text present between the anchor tags
        System.out.println(var.getAttribute("href"));
        hrefs.add(var.getAttribute("href")); 
        System.out.println("*************************************");
    }

    //Navigating to each link
    int i=0;
    for (String href : hrefs) {
        driver.navigate().to(href);
        System.out.println((++i)+": navigated to URL with href: "+href);
        Thread.sleep(3000); // To check if the navigation is happening properly.
        System.out.println("+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
    }
static WebDriver driver=null;
public static void main(String[] args) throws IOException 
{     System.setProperty("webdriver.chrome.driver","D:\\softwaretesting\\broswer driver\\chromedriver.exe");
        WebDriver driver = new ChromeDriver();``
        driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
        //driver.manage().window().maximize();
        driver.get("http://google.com/");      
        List<WebElement> links=driver.findElements(By.tagName("a"));            
        System.out.println("Total links are "+links.size());            
        for(int i=0;i<links.size();i++)
        {       
            WebElement ele= links.get(i);               
            String url=ele.getAttribute("href");                
            verifyLinkActive(url);          
        }        
    }       
    public static void verifyLinkActive(String linkUrl)
    {           try 
        {
           URL url = new URL(linkUrl);             
           HttpURLConnection httpURLConnect=(HttpURLConnection)url.openConnection();               
           httpURLConnect.setConnectTimeout(3000);             
           httpURLConnect.connect();               
           if(httpURLConnect.getResponseCode()==200)               {
               System.out.println(linkUrl+" - "+httpURLConnect.getResponseMessage());
               File src= (TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);     
               FileUtils.copyFile(src, new File("D://screenshort//Spiritualbridge//"+System.currentTimeMillis()+".png"));   
            }             if(httpURLConnect.getResponseCode()==HttpURLConnection.HTTP_NOT_FOUND)  
           {
               System.out.println(linkUrl+" - "+httpURLConnect.getResponseMessage() + " - "+ HttpURLConnection.HTTP_NOT_FOUND);
            }                
        }           catch (Exception e) 
        {              
        }       
    }   

暂无
暂无

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

相关问题 如何使用Selenium WebDriver逐个获取所有链接并单击这些链接 - How to fetch all links and click those links one by one using Selenium WebDriver 在 Selenium webdriver 中单击一个链接后如何获得新出现的链接? - How to get new appearing links after clicking one in Selenium webdriver? Selenium Webdriver:如何单击这些链接? - Selenium webdriver: How can I click these links? 提取特定类硒Webdriver下/中的所有链接(java) - fetch all links under/in a specific class-selenium webdriver (java) 无法使用Java和Selenium Webdriver单击网页上的所有链接 - Not able to click all links on a web page using Java and Selenium Webdriver 如何在selenium webdriver中从网页中提取所有链接后单击特定链接 - How to click on specific link after extracting all the links from a web page in selenium webdriver 如何验证链接并在Selenium Webdriver Java中单击链接 - How to verify links and click on them in Selenium webdriver Java WebDriver脚本,用于单击除特定名称不起作用的所有链接 - WebDriver script for clicking all links except one with particular name not working java,Webdriver,我想获取网页中的所有链接,然后将它们与我拥有的字符串名称进行比较,如果找到它,则单击它 - 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 如何通过selenium webdriver访问链接特定部分的链接 - How to access links in the specific section of links through selenium webdriver
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM