如何在Selenium WebDriver中单击网页中的所有链接

时间:2014-02-20 05:02:44

标签: selenium-webdriver

我有10个不同的页面包含不同的链接。如何点击所有链接?

条件是: i)我不知道有多少链接 ii)我想计算并点击每个链接

请建议我使用Selenium WebDriver脚本。

8 个答案:

答案 0 :(得分:8)

捕获并浏览网页上的所有链接

Iterator和高级for循环可以做类似的工作;但是,循环中页面导航的不一致性可以使用数组概念来解决。

private static String[] links = null;
private static int linksCount = 0;

driver.get("www.xyz.com");
List<WebElement> linksize = driver.findElements(By.tagName("a")); 
linksCount = linksize.size();
System.out.println("Total no of links Available: "+linksCount);
links= new String[linksCount];
System.out.println("List of links Available: ");  
// print all the links from webpage 
for(int i=0;i<linksCount;i++)
{
links[i] = linksize.get(i).getAttribute("href");
System.out.println(all_links_webpage.get(i).getAttribute("href"));
} 
// navigate to each Link on the webpage
for(int i=0;i<linksCount;i++)
{
driver.navigate().to(links[i]);
Thread.sleep(3000);
}

1 |捕获特定帧| class | id下的所有链接并逐个导航

driver.get("www.xyz.com");  
WebElement element = driver.findElement(By.id(Value));
List<WebElement> elements = element.findElements(By.tagName("a"));
int sizeOfAllLinks = elements.size();
System.out.println(sizeOfAllLinks);
for(int i=0; i<sizeOfAllLinks ;i++)
{
System.out.println(elements.get(i).getAttribute("href"));
}   
for (int index=0; index<sizeOfAllLinks; index++ ) {
getElementWithIndex(By.tagName("a"), index).click();
driver.navigate().back();
}

public WebElement getElementWithIndex(By by, int index) {
WebElement element = driver.findElement(By.id(Value));
List<WebElement> elements = element.findElements(By.tagName("a")); 
return elements.get(index);
}

2 |捕获所有链接[替代方法]

的Java

driver.get(baseUrl + "https://www.google.co.in");
List<WebElement> all_links_webpage = driver.findElements(By.tagName("a")); 
System.out.println("Total no of links Available: " + all_links_webpage.size());
int k = all_links_webpage.size();
System.out.println("List of links Available: ");
for(int i=0;i<k;i++)
{
if(all_links_webpage.get(i).getAttribute("href").contains("google"))
{
String link = all_links_webpage.get(i).getAttribute("href");
System.out.println(link);
}   
}

的Python

from selenium import webdriver

driver = webdriver.Firefox()
driver.get("https://www.google.co.in/")
list_links = driver.find_elements_by_tag_name('a')

for i in list_links:
        print i.get_attribute('href')

driver.quit()

答案 1 :(得分:3)

public static void main(String[] args) 
    {
        FirefoxDriver fd=new FirefoxDriver();
        fd.get("http:www.facebook.com");
        List<WebElement> links=fd.findElements(By.tagName("a"));
        System.out.println("no of links:" +links.size());

        for(int i=0;i<links.size();i++)
        {
            if(!(links.get(i).getText().isEmpty()))
            {
            links.get(i).click();
            fd.navigate().back();
            links=fd.findElements(By.tagName("a"));
            }       
        }
   }

此程序点击链接,导航回页面并再次点击第二个链接。

答案 2 :(得分:0)

将它们存储在一个数组中,然后单击它们:

   ArrayList<WebElement> input_type = (ArrayList<WebElement>)    
  driver.findElements(By.tagName("a"));

 for (WebElement type : input_type)
 {


      type.click();


  }

这将逐个点击带有标签的所有链接,我希望你明白这一点。享受!

答案 3 :(得分:0)

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;

import org.openqa.selenium.firefox.FirefoxProfile;

import org.openqa.selenium.firefox.internal.ProfilesIni;

public class Find_all_Links {

private static String testUrl = "http://www.google.co.in/";

private static WebDriver driver = null;

public static void main(String[] args) {

    ProfilesIni profile = new ProfilesIni();

    FirefoxProfile myProfile = profile.getProfile("AutomationQA");

    driver = new FirefoxDriver(myProfile);

    driver.get(testUrl);

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

    System.out.println(oLinksOnPage.size());

    for(int i=0;i<oLinksOnPage.size();i++){

        System.out.println(oLinksOnPage.get(i).getText());
    }


}

}

答案 4 :(得分:0)

package selenium.tests;

import java.util.List;



import java.util.concurrent.TimeUnit;
import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

public class TestAllLinks { 



 public static void main(String[] args) {
        String baseUrl = "http://www.qaautomated.com/";
        System.setProperty("webdriver.chrome.driver", 

         "C:\\Users\\chromedriver_win32\\chromedriver.exe");
        WebDriver driver=new ChromeDriver();
        String notWorkingUrlTitle = "Under Construction: QAAutomated";
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

        driver.get(baseUrl);
        List<WebElement> linkElements = driver.findElements(By.tagName("a"));
        String[] linkTexts = new String[linkElements.size()];
        int i = 0;

        //extract the link texts of each link element
        for (WebElement elements : linkElements) {
            linkTexts[i] = elements.getText();
            i++;
        }

        //test each link
        for (String t : linkTexts) {
            driver.findElement(By.linkText(t)).click();
            if (driver.getTitle().equals(notWorkingUrlTitle )) {
                System.out.println("\"" + t + "\""
                        + " is not working.");
            } else {
                System.out.println("\"" + t + "\""
                        + " is working.");
            }
            driver.navigate().back();
        }
        driver.quit();
    }
}

http://www.qaautomated.com/2016/10/selenium-test-to-check-links-in-web.html

答案 5 :(得分:0)

您可以使用2个逻辑来处理

  1. 获取链接并在浏览器中点击并验证
  2. 获取链接并使用REST Web服务验证链接。
  3. 使用REST WS将是验证链接的最简单方法。

    下面的代码对我来说很好。

    public class Testing{
    
        public static void main(String[] args) {
            try{
                WebDriver driver = new FirefoxDriver();
                driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
                driver.manage().window().maximize();
                driver.navigate().to("https://www.amazon.in/");
                List<WebElement> links = driver.findElements(By.tagName("a"));
                System.out.println("Number of links : " + links.size());
                for(WebElement e : links) {
                    String linkText = e.getAttribute("href");
                    System.out.println("Link -->>" +linkText);
                    if(linkText!=null && !linkText.isEmpty()) {
                        HttpPost post = new HttpPost(linkText);
                        HttpClient client = HttpClientBuilder.create().build();
                        HttpResponse res = client.execute(post);
                        String s = res.getStatusLine().toString();
                        if(s.equals("HTTP/1.1 200 OK")) {
                            System.out.println("Navigated");
                            //your code to handle logic 
                        } else {
                            //your code to handle logic with other response code
                        }
                    }
                }
            } catch (Exception e) {
                System.out.println(e.getStackTrace());
            }
        }    
    }
    

答案 6 :(得分:0)

将最后的答案分成几行:

在Python中:

\s

答案 7 :(得分:0)

不确定效率如何,但是每次迭代后我都将链接重新加载到同一列表中,并成功完成了任务。

String baseURL = "https://www.wikipedia.org/";

        driver.get(baseURL);
        List<WebElement> links = driver.findElements(By.xpath("//div[@class='central-featured']/div/a")); 
        System.out.println("The size of the list is: " + links.size());

        // Loop through links, click on each link, navigate back, reload the link and
        // continue.

        for (int i = 0; i < links.size(); ++i) {
            links.get(i).click();
            driver.navigate().back();
            // reloading the list or there will be stale-element exception
            links = driver.findElements(By.xpath("//div[@class='central-featured']/div/a"));

        }
        // print the link text and href values

        for (int i = 0; i < links.size(); ++i) {
            System.out.print(links.get(i).getText() + "--> " + links.get(i).getAttribute("href"));
        }

        driver.close();