Java 为什么Selenium中的WebElements列表在driver.get(“URL”)之后变为空?

Java 为什么Selenium中的WebElements列表在driver.get(“URL”)之后变为空?,java,selenium,selenium-webdriver,webdriver,selenium-chromedriver,Java,Selenium,Selenium Webdriver,Webdriver,Selenium Chromedriver,我面临一个奇怪的问题。此代码工作正常。 它打印页面上的所有超链接 import org.openqa.selenium.*; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.chrome.ChromeOptions; import java.util.List; public class MyMain { public static We

我面临一个奇怪的问题。此代码工作正常。 它打印页面上的所有超链接


    import org.openqa.selenium.*;
    import org.openqa.selenium.chrome.ChromeDriver;
    import org.openqa.selenium.chrome.ChromeOptions;
    import java.util.List;
    public class MyMain {
        public static WebDriver driver;
        public static List<WebElement> aList;//the list of all elements with tag <a>
        public static void main(String[] args)  {
            ChromeOptions options = new ChromeOptions();
            options.addArguments("--disable-notifications"); //disable popup alerts from chrome
            System.setProperty("webdriver.chrome.driver", "D:\\selenium\\drivers\\chromedriver.exe");
            driver = new ChromeDriver(options);
            driver.manage().window().maximize();
            int counter = 0; // number of elements in aList just for debug
            String hrefAttribute = "";
            driver.get("https://www.zap.co.il/");
            aList = driver.findElements(By.tagName("a"));
            System.out.println(aList.size());//just for debug
            for (int i = 0; i < aList.size(); i ++ ) {
            hrefAttribute = aList.get(i).getAttribute("href");
             if (hrefAttribute != null) {             
                        System.out.println(hrefAttribute);
                        counter +=1;                  
                }
            }
            System.out.println(counter);
            driver.close();
            driver.quit();

我通过添加以下内容解决了此问题:

   

    if (hrefAttribute != null) {
               driver.get(hrefAttribute);
                    System.out.println(hrefAttribute);
                    counter +=1;
                    driver.get("https://www.zap.co.il/"); //here the list becomes empty!!!  
                    aList = driver.findElements(By.tagName("a"));//this fixed the issue.But WHY?
            }

如果有人能向我解释这种奇怪的行为,我将不胜感激

WebElements列表变为空(保持162的大小不变) 元素)

我怀疑这个列表是否真的变为“空”;事实上,你自己说它仍然包含162个元素。我怀疑您的Web元素变得“过时”(至少在我使用的C#中会出现这种情况)


WebElement对象连接到浏览器中的实时加载页面,因此当您加载其他页面时,所有现有WebElement对象都会“过时”;它们不再连接到实际的HTML元素。

它是否会引发过时的元素引用异常。因为您的DOM将重新加载? 或者它根本不进入循环

第二行修复了这个问题,因为它再次获取了带有标记的所有元素

   

    if (hrefAttribute != null) {
               driver.get(hrefAttribute);
                    System.out.println(hrefAttribute);
                    counter +=1;
                    driver.get("https://www.zap.co.il/"); //here the list becomes empty!!!  
                    aList = driver.findElements(By.tagName("a"));//this fixed the issue.But WHY?
            }