【问题标题】:How to use selenium to extract elements from expandable section如何使用硒从可扩展部分中提取元素
【发布时间】:2019-09-09 09:19:33
【问题描述】:

我正在学习如何使用 selenium从网页中提取数据。我试图从页面https://www.redfin.com/CA/Los-Angeles/1366-W-22nd-St-90007/home/6896268 中提取的数据是日期,例如2018 年 10 月 29 日。所有日期都在 html 表格“1366 West 22nd St”的第一列中。

但是,使用以下代码,我只能从表中获取前三个日期

cell = driver.find_element(By.XPATH, '//table[@class="basic-table-2"]/tbody/tr[1]/td[1]')

由于表格是折叠的,我需要点击部分底部链接查看所有属性历史链接来展开表格并查看此表格中的其余日期。有没有办法使用 selenium 从表中获取所有日期,包括折叠行中的日期?

【问题讨论】:

    标签: selenium css-selectors webdriver java-stream webdriverwait


    【解决方案1】:

    website 上单击元素为查看所有属性历史记录 以展开表格并从表格中提取您需要诱导的日期WebDriverWait然后使用 Java8stream()map() 可以使用以下解决方案:

    • 代码块:

      driver.get("https://www.redfin.com/CA/Los-Angeles/1366-W-22nd-St-90007/home/6896268");
      ((JavascriptExecutor)driver).executeScript("return arguments[0].scrollIntoView(true);", new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("section#property-history-scroll h2.h2"))));
      new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.cssSelector("span.bottomLink"))).click();
      List<String> myDates = new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfAllElementsLocatedBy(By.cssSelector("section#property-history-scroll tbody tr.PropertyHistoryEventRow[id^='propertyHistory-']>td.date-col"))).stream().map(element->element.getAttribute("innerHTML")).collect(Collectors.toList());
      System.out.println(myDates);
      
    • 控制台输出:

      [Oct 29, 2018, Aug 24, 2018, Aug 24, 2018, Jul 24, 2018, Mar 18, 2018, Dec 31, 2015, Sep 11, 2015, Jul 10, 2015, May 22, 2015, May 20, 1988, Aug 10, 1979]
      

    【讨论】:

      【解决方案2】:

      您必须先点击“查看全部”链接才能获得这些日期。在列表展开之前,它们根本不在 DOM 中。但是点击很容易:

      driver.find_element(By.CLASS_NAME, 'bottomLink').click()
      

      【讨论】:

        猜你喜欢
        • 2013-09-14
        • 2019-08-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-12-23
        • 2022-07-09
        • 1970-01-01
        相关资源
        最近更新 更多