首页 > 解决方案 > 将从不同网页抓取的数据附加到数组列表中

问题描述

我正在从事一个涉及从网站上抓取数据的项目,但遇到了问题。我想从一个网页中抓取数据,将其附加到一个数组列表中,然后让爬虫移动到下一页并执行相同的操作,依此类推,但是当我执行我的代码时,前面附加的数据被覆盖,最后我仅从最终网页中抓取数据。我也遇到一个错误:线程“main”org.openqa.selenium.StaleElementReferenceException 中的异常:过时的元素引用:元素未附加到页面文档(会话信息:chrome=71.0.3578.98)(驱动程序信息:chromedriver=2.42.591059(a3d9684d10d61aa0c45f6723b327283be1ebaad8),平台=Mac OS X 10.13.6 x86_64)(警告:服务器未提供任何堆栈跟踪信息)命令持续时间或超时:0 毫秒

下面是我的代码和日志。请帮忙。谢谢你。以下内容抓取数据并将其附加到数组列表中:

do {

        row = (ArrayList<WebElement>) driver.findElements(By.cssSelector(".event-row-container.ng-scope"));

        WebElement element = driver.findElement(By.cssSelector(".paybillnumbers"));
        ((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView(true);", element);
        try {
            Thread.sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }


        new WebDriverWait(driver,20).until(ExpectedConditions.elementToBeClickable(By.cssSelector("li.ng-scope[translate='next']"))).click();
        times++;
        rows.addAll(row);
        }
        while(times <=6);

这是日志将错误引用到的代码:

                ArrayList<WebElement> rowDetails2 = (ArrayList<WebElement>) rowDetails.findElements(By.cssSelector(".event-market.market-3-way.market-selections-3"));

这是我的日志:

在端口 3035 上启动 ChromeDriver 2.42.591059 (a3d9684d10d61aa0c45f6723b327283be1ebaad8) 只允许本地连接。2018 年 12 月 18 日上午 11:18:53 org.openqa.selenium.remote.ProtocolHandshake createSession INFO:检测到的方言:OSS 正在启动 ChromeDriver 2.42.591059 (a3d9684d10d61aa0c45f6723b327283be1ebaad8) 端口 24080 仅允许本地连接。2018 年 12 月 18 日上午 11:18:58 org.openqa.selenium.remote.ProtocolHandshake createSession INFO:检测到方言:线程“主”org.openqa.selenium.StaleElementReferenceException 中的 OSS 98 异常:过时元素引用:元素未附加到页面文档(会话信息:chrome=71.0.3578.98)(驱动程序信息:chromedriver=2.42.591059(a3d9684d10d61aa0c45f6723b327283be1ebaad8),平台=Mac OS X 10.13.6 x86_64)(警告:

标签: javaseleniumarraylistweb-scrapingappend

解决方案


对于 StaleElementReferenceException 我们需要使用等待

    new WebDriverWait(driver, 60).until(ExpectedConditions.presenceOfAllElementsLocatedBy(By.cssSelector(".event-market.market-3-way.market-selections-3")));

这里 60 是最大秒数,您可以更改。定位器也包含数字 3,执行时更改定位器可能会发生变化,因此请查看。

如果等待失败,您也可以在 java 中使用 Thread.sleep。

参考这个


推荐阅读