简体   繁体   English

如何使用Selenium WebDriver逐个获取所有链接并单击这些链接

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

I am using Selenium WebDriver with java. 我正在使用Selenium WebDriver和java。

I am fetching all links from webpage and trying to click each link one by one. 我从网页上获取所有链接,并尝试逐个点击每个链接。 I am getting below error: 我收到以下错误:

error org.openqa.selenium.StaleElementReferenceException: Element not found in the cache - perhaps the page has changed since it was looked up Command duration or timeout: 30.01 seconds For documentation on this error, please visit: http://seleniumhq.org/exceptions/stale_element_reference.html Build info: version: '2.25.0', revision: '17482', time: '2012-07-18 21:09:54' 错误org.openqa.selenium.StaleElementReferenceException:在缓存中找不到元素 - 自查询以来页面可能已更改命令持续时间或超时:30.01秒有关此错误的文档,请访问: http//seleniumhq.org/ exceptions / stale_element_reference.html构建信息:版本:'2.25.0',修订版:'17482',时间:'2012-07-18 21:09:54'

and here is my code : 这是我的代码:

public void getLinks()throws Exception{
    try {
        List<WebElement> links = driver.findElements(By.tagName("a"));
        int linkcount = links.size(); 
         System.out.println(links.size()); 
          for (WebElement myElement : links){
         String link = myElement.getText(); 
         System.out.println(link);
         System.out.println(myElement);   
        if (link !=""){
             myElement.click();
             Thread.sleep(2000);
             System.out.println("third");
            }
            //Thread.sleep(5000);
          } 
        }catch (Exception e){
            System.out.println("error "+e);
        }
    }

actually, it's displaying in output 实际上,它在输出中显示

[[FirefoxDriver: firefox on XP (ce0da229-f77b-4fb8-b017-df517845fa78)] -> tag name: a] [[FirefoxDriver:XP上的firefox(ce0da229-f77b-4fb8-b017-df517845fa78)] - >标签名称:a]

as link, I want to eliminate these form result. 作为链接,我想消除这些形式的结果。

There is no such a good idea to have following scenario : 有以下场景没有这么好的主意:

for (WebElement element : webDriver.findElements(locator.getBy())){
  element.click();
}

Why? 为什么? Because there is no guarantee that the element.click(); 因为无法保证element.click(); will have no effect on other found elements, so the DOM may be changed, so hence the StaleElementReferenceException . 对其他找到的元素没有影响,因此DOM可能会被更改,因此StaleElementReferenceException也是StaleElementReferenceException

It is better to use the following scenario : 最好使用以下方案:

int numberOfElementsFound = getNumberOfElementsFound(locator);
for (int pos = 0; pos < numberOfElementsFound; pos++) {
  getElementWithIndex(locator, pos).click();
}

This is better because you will always take the WebElement refreshed, even the previous click had some effects on it. 这样更好,因为您将始终刷新WebElement ,即使之前的点击也会对其产生一些影响。

EDIT : Example added 编辑:添加示例

  public int getNumberOfElementsFound(By by) {
    return webDriver.findElements(by).size();
  }

  public WebElement getElementWithIndex(By by, int pos) {
    return webDriver.findElements(by).get(pos);
  }

Hope to be enough. 希望足够。

Credit goes to "loan". 信用归于“贷款”。

I am also getting "stale exception" so I used 'loan' answer and works perfectly. 我也得到“陈旧的例外”所以我使用'贷款'答案并且完美地工作。 Just if anyone need to know how to click on each link from results page try this (java) 如果有人需要知道如何从结果页面点击每个链接试试这个(java)

clickAllHyperLinksByTagName("h3"); where "h3" tag contains hyperlink 其中“h3”标签包含超链接

 public static void clickAllHyperLinksByTagName(String tagName){
    int numberOfElementsFound = getNumberOfElementsFound(By.tagName(tagName));
    System.out.println(numberOfElementsFound);
    for (int pos = 0; pos < numberOfElementsFound; pos++) {
        getElementWithIndex(By.tagName(tagName), pos).click();
        driver.navigate().back();
    }
}

public static int getNumberOfElementsFound(By by) {
    return driver.findElements(by).size();
}

public static WebElement getElementWithIndex(By by, int pos) {
    return driver.findElements(by).get(pos);
}
    WebDriver _driver = new InternetExplorerDriver();
    _driver.navigate().to("http://www.google.co.in/");
    List <WebElement> alllinks = _driver.findElements(By.tagName("a"));

    for(int i=0;i<alllinks.size();i++)
        System.out.println(alllinks.get(i).getText());

    for(int i=0;i<alllinks.size();i++){
        alllinks.get(i).click();
        _driver.navigate().back();
    }

If you're OK using WebDriver.get() instead of WebElement.click() to test the links, an alternate approach is to save the href value of each found WebElement in a separate list. 如果您可以使用WebDriver.get()而不是WebElement.click()来测试链接,则另一种方法是将每个找到的WebElementhref值保存在单独的列表中。 This way you avoid the StaleElementReferenceException because you're not trying to reuse subsequent WebElement s after navigating away with the first WebElement.click() . 这样就可以避免StaleElementReferenceException因为在使用第一个WebElement.click()导航之后,您不会尝试重用后续的WebElement

Basic example: 基本示例:

List<String> hrefs = new ArrayList<String>();
List<WebElement> anchors = driver.findElements(By.tagName("a"));
for ( WebElement anchor : anchors ) {
    hrefs.add(anchor.getAttribute("href"));
}
for ( String href : hrefs ) {
    driver.get(href);           
}
//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();
    }

For complete Explanation Read This POST 完整说明阅读此POST

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

System.out.println("Total number of page on the webpage:"+ linkCount);
String[] texts=new String[linkCount];
int t=0;
for (WebElement text:links){
  texts[t]=text.getText();//extract text from link and put in Array
  //System.out.println(texts[t]);
  t++;
}
for (String clicks:texts) {

  driver.findElement(By.linkText(clicks)).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();

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

相关问题 如何使用Selenium WebDriver来获取所有链接并单击一个链接 - How to fetch all links and click those links one by one with Selenium WebDriver 无法使用Java和Selenium Webdriver单击网页上的所有链接 - Not able to click all links on a web page using Java and 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) 获取网页中的所有非隐藏链接,然后使用Selenium Webdriver单击 - Get all the non-hidden links in a webpage and click using 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 如何使用 selenium java 点击图像上的链接 - how to click on links on images using selenium java WebDriver脚本,用于单击除特定名称不起作用的所有链接 - WebDriver script for clicking all links except one with particular name not working
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM