java - Selenium Java 代码打印 google 搜索的前五个结果

标签 java selenium selenium-webdriver

线程“main”中出现异常org.openqa.selenium.StaleElementReferenceException:陈旧元素引用:元素未附加到页面文档 ( session 信息:chrome=83.0.4103.106) 有关此错误的文档,请访问:https://www.seleniumhq.org/exceptions/stale_element_reference.html 构建信息:版本:'3.141.59',修订版:'e82be7d358',时间:'2018-11-14T08:25:53' 驱动程序信息:org.openqa.selenium.chrome.ChromeDriver 功能{acceptInsecureCerts:false,browserName:chrome,browserVersion:83.0.4103.106,chrome:{chromedriverVersion:83.0.4103.39(ccbf011cb2d2b ...,userDataDir:C:\Users\MOHAMM〜1\AppData\L ...},goog :chromeOptions:{debuggerAddress:localhost:53846},javascriptEnabled:true,networkConnectionEnabled:false,pageLoadStrategy:正常,平台:WINDOWS,platformName:WINDOWS,代理:Proxy(),setWindowRect:true,strictFileInteractability:false,超时:{隐式: 0,pageLoad:300000,脚本:30000},unhandledPromptBehavior:解雇并通知,webauthn:virtualAuthenticators:true} session ID:f9fd73fa86d306099bad2835337c25c0 *** 元素信息:{Using=xpath, value=//h3[@class='LC20lb DKV0Md']}

Code snap shot

显示第一页的结果,但当我单击第二页结果时,我收到 StaleElementReferenceException

import java.util.List;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

public class NavigateToGoogle {

    public static void main(String[] args) throws InterruptedException {
        // TODO Auto-generated method stub
        WebDriver driver = new ChromeDriver();
        driver.get("http://www.google.com");
        driver.manage().window().maximize();
        driver.manage().timeouts().implicitlyWait(10,TimeUnit.SECONDS);
        //driver.findElement(By.xpath("//input[@class='gLFyf gsfi'])")).sendKeys("zahid");

        WebElement element=driver.findElement(By.name("q"));
        element.sendKeys("mohammed zahid");
        //element.click();
        Thread.sleep(3000);
        //driver.findElement(By.xpath("(//input[@type='submit'])[3]")).click();
        List<WebElement> button=driver.findElements(By.name("btnK"));
        System.out.println(button.size());
        WebElement submit=driver.findElement(By.name("btnK"));
        submit.submit();

        WebElement matchingRes=driver.findElement(By.xpath("//h3[@class='LC20lb DKV0Md']"));
        List<WebElement> listRes=matchingRes.findElements(By.xpath("//h3[@class='LC20lb DKV0Md']"));
        System.out.println(listRes.size());
        for(WebElement results:listRes) 
        {
            String value = results.getText();
            System.out.println(value);
        }

        driver.findElement(By.xpath("//a[@aria-label='Page 2']")).click();
        WebDriverWait wait = new WebDriverWait(driver, 5);
        wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//h3[@class='LC20lb DKV0Md']")));
        WebElement matchingRes1=driver.findElement(By.xpath("//h3[@class='LC20lb DKV0Md']")); 
        matchingRes1.getSize();
        List<WebElement> listRes1=matchingRes.findElements(By.xpath("//h3[@class='LC20lb DKV0Md']")); 
        System.out.println(listRes1.size());

        for(WebElement results1:listRes1)
        {
            String value = results1.getText();
            System.out.println(value);
        }
    }

}

最佳答案

我们无法对谷歌结果页面元素进行硬编码,因为每个谷歌页面都在日复一日地更新。这里我已经给出了带有示例代码的结果搜索,你可以尝试这个(我正在启动谷歌页面并输入“测试”并显示所有结果然后从列表中单击“测试类型”,如果您需要所有结果,可以打印)

 public static void main(String[] args) throws Exception {
    System.setProperty("webdriver.chrome.driver", "C:\\Users\\User\\Downloads\\Chromedriver\\chromedriver.exe");
    WebDriver driver = new ChromeDriver();
    driver.manage().window().maximize();
    driver.get("https://www.google.com/");
    driver.findElement(By.name("q")).sendKeys("Testing");
    Thread.sleep(Long.parseLong("1000"));
    List<WebElement> LIST = driver.findElements(By.xpath("//ul[@role='listbox']//li/descendant::div[@class='sbl1']"));
    System.out.println(LIST.size());


    for (int i = 0; i < LIST.size(); i++)
    {
        //System.out.println(LIST.get(i).getText());
        if (LIST.get(i).getText().contains("testing types"))
        {
            LIST.get(i).click();
            break;
        }
    }
}

}

关于java - Selenium Java 代码打印 google 搜索的前五个结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62450394/

相关文章:

python - 使用 Mechanize for python,需要可以右键

selenium - 我无法使用 Selenium 在谷歌浏览器中打开新标签

python - Selenium 失败,错误为 : Service geckodriver unexpectedly exited. 状态代码为:2

java - Selenium 网络驱动程序 : sometimes sends keys to wrong field

java:将枚举注入(inject)应用程序范围

java - SQL 注入(inject)从 Hibernate HQL 到 MySQL 的删除/删除

java - 确定证书签名请求是使用 SHA1 算法还是 SHA2 算法发出

java - 下载 jeromq 二进制文件的信誉良好的位置?

java - Geckodriver 无法在 Mac OS X 上启动

selenium - 是否有适用于 Microsoft Edge 浏览器的 Selenium WebDriver?