【问题标题】:Append data scraped from different webpages into an arraylist将从不同网页抓取的数据附加到数组列表中
【发布时间】:2018-12-18 17:32:54
【问题描述】:

我正在从事一个涉及从网站抓取数据的项目,但遇到了问题。我想从一个网页中抓取数据,将其附加到一个数组列表中,然后让爬虫移动到下一页并执行相同的操作,依此类推,但是当我执行我的代码时,前面附加的数据被覆盖,最后我仅从最终网页中抓取数据。 我也遇到一个错误:线程“main”中的异常 org.openqa.selenium.StaleElementReferenceException: stale element reference: element is not attach to the page document (会话信息:chrome=71.0.3578.98) (驱动程序信息:chromedriver=2.42.591059 (a3d9684d10d61aa0c45f6723b327283be1ebaad8),platform=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 信息:检测到的方言:OSS 在端口 24080 上启动 ChromeDriver 2.42.591059 (a3d9684d10d61aa0c45f6723b327283be1ebaad8) 只允许本地连接。 2018 年 12 月 18 日上午 11:18:58 org.openqa.selenium.remote.ProtocolHandshake createSession 信息:检测到的方言:OSS 98 线程“主”org.openqa.selenium.StaleElementReferenceException 中的异常:过时的元素引用:元素未附加到页面文档 (会话信息:chrome=71.0.3578.98) (驱动程序信息:chromedriver=2.42.591059 (a3d9684d10d61aa0c45f6723b327283be1ebaad8),platform=Mac OS X 10.13.6 x86_64)(警告:服务器未提供任何堆栈跟踪信息) 命令持续时间或超时:0 毫秒

【问题讨论】:

    标签: java selenium arraylist web-scraping append


    【解决方案1】:

    对于 StaleElementReferenceException 我们需要使用等待

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

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

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

    参考this

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-11-29
      • 2020-09-12
      • 1970-01-01
      • 2021-10-15
      • 2020-05-10
      • 2021-01-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多