簡體   English   中英

無法使用Java在Selenium Webdriver中單擊網頁上的多個鏈接

[英]Unable to click on multiple links on a webpage in selenium webdriver with java

我的密碼

WebDriver driver = new FirefoxDriver();
driver.get("https://google.com");
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(10,TimeUnit.SECONDS);
driver.findElement(By.name("q")).sendKeys("selenium");
driver.findElement(By.xpath("//button[@value='Search']")).click();

List<WebElement> alllinks = driver.findElements(By.xpath("//div[3][@class='_NId']/div/div/div/h3"));

for(WebElement cl:alllinks)
{
    System.out.println(cl.getText());

    if(cl.getText()!="")
    {
        cl.click();
    }

}

通過上面的代碼,我沒有任何異常,但是我也無法單擊網頁上的任何鏈接,我只想一個一個地單擊每個鏈接。請提前告訴我解決方案。

您假設打開所有鏈接是正確的,但是代碼無法將所需的輸出顯示為

1>當Google搜索結果顯示為“ Selenium”關鍵字時,您在那邊有很多鏈接。 因此,如果您手動單擊每個鏈接-它會在同一選項卡中打開,其他鏈接將無法訪問,因為WebDriver為您提供了org.openqa.selenium.StaleElementReferenceException:異常。

現在嘗試以下代碼:

        open some driver
        driver.get("https://google.com");
        driver.manage().window().maximize();
        driver.manage().timeouts().implicitlyWait(10,TimeUnit.SECONDS);
        driver.findElement(By.name("q")).sendKeys("selenium");
        driver.findElement(By.xpath("//button[@value='Search']")).click();

        List<WebElement> alllinks = driver.findElements(By.xpath("//div[3][@class='_NId']/div/div/div/h3"));

        for(WebElement cl:alllinks)
        {
            System.out.println(cl.getText());
            if(cl.getText()!="")
            {
                Actions action = new Actions(driver); // I have added these lines
                action.keyDown(Keys.CONTROL).moveToElement(cl).click().perform();
                action.keyUp(Keys.CONTROL).perform();
            }
         }

因此,現在所有鏈接都將在新選項卡中打開,並且可以使用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM