首页 > 解决方案 > 使用 selenium webdriver 滚动/加载动态表

问题描述

我正在尝试从未完全加载的动态表中获取所有行。它有近 2k 行,所以我需要向下滚动以加载表,然后我需要从 xpath 获取所有元素。这是我的代码块:

    try:
    elem = driver.find_element_by_xpath("//table[@class = 'ng-scope ng-table']")
    for _ in range(50):
        driver.execute_script("arguments[0].scrollIntoView();", elem)
        driver.implicitly_wait(0.2)
    except Exception as e:
        print ("Error scrolling down web element = " + str(e))
        driver.quit()

    # To get all elements in table (It only takes first 25 since others could not be loded without scrolling)
    elements = wait.until(EC.visibility_of_all_elements_located((By.XPATH, "//div[@class = 'scrolly-table']//tr[@class = 'base ng-scope']")))

但它的作用是把桌面放到屏幕上。即使我尝试在放置一些睡眠点的同时手动滚动它,它也会再次滚动到表格顶部。既不给出错误也不滚动表格。

欢迎所有建议

标签: pythonhtmlseleniumscrollwebdriver

解决方案


当我尝试在滚动/加载表上获取元素时,这对我有用:

1-单击表格以选择它:

driver.find_element_by_xpath('//*[@id="table_id"]/tbody').click()

2-向下滚动整个页面:

driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")

3- 就我而言,tr 元素在 tbody 中按 30 分组。所以我的代码基于获取 tbody 的 trs 的循环,然后在表格中滚动:

trs = []
x = 1
while x <= tbody:
        lines = driver.find_elements_by_xpath('//*[@id="table_id"]/tbody[%s]/tr' % x)
        for line in lines:
            tr = CDMTransaction()
            tr.label = line.find_element_by_xpath('.//td[5]/span').text
            trs.append(tr)

        x += 1
        actions = ActionChains(self.driver)
        actions.send_keys(Keys.SPACE).perform()
        actions.send_keys(Keys.SPACE).perform()
        time.sleep(1)

推荐阅读