【问题标题】:How to perform selenium automation of an auto refreshing web page (every 5s)?如何执行自动刷新网页(每 5 秒)的硒自动化?
【发布时间】:2019-02-18 08:05:55
【问题描述】:

我正在使用 Chrome 自动化一个由一个非常大的表格(300 多行)组成的网页。表格内容每 5 秒刷新一次。在 selenium 完成所有行的遍历之前,表会被刷新。例如,如果 selenium 遍历了 50 行,然后表被刷新,第 51 行将引发 StaleElementReferenceException。 我不知道需要修改哪些功能才能获取内容。

我已尝试禁用 javascript 并运行自动化脚本。但是,禁用 javascript 会导致 chrome 驱动出现问题。

def table_get():
    header_list = list()
    return_list = list()

    head = driver.find_elements_by_tag_name('thead')
    body = driver.find_elements_by_tag_name('tbody')

    for row in head.find_elements_by_tag_name('tr'):
        for header in row.find_elements_by_tag_name('th'):
            header_list.append(th.text)

    for row in body.find_elements_by_tag_name('tr'):
        temp_list = list()
        for cell in row.find_elements_by_tag_name('td'):
            temp_list.append(cell.text)
        return_list.append(zip(header_list, temp_list))

    return return_list

预期输出:遍历所有行并返回字典列表,其中每个字典键是表头,值是表头下的行内容。

实际输出:遍历无法完成。在遍历之间抛出 StaleElementReferenceException。

【问题讨论】:

  • 所以基本上,如果我理解正确,您正在寻找的是一种在 5 秒内获取所有表数据的方法,对吗?
  • 并非如此。在我看来,使用 selenium 在 5 秒内捕获如此大的表数据可能是不可能的。禁用网页上的自动刷新功能可能是一个可行的解决方案。
  • 是的,禁用它是可能的。尽管您可能需要考虑禁用刷新的影响——您将使用过时的数据。你的用例可以吗?如果是这样,您是否能够隔离刷新表的内容,以便我们找到解决方案来禁用它?

标签: python selenium selenium-webdriver


【解决方案1】:

使用 Javascript 获取如下示例中的数据,hereherehere

headers = driver.execute_script('return [...document.querySelectorAll("thead tr th")].map(e=>e.textContent)')
cells = driver.execute_script('return [...document.querySelectorAll("tbody tr td")].map(e=>e.textContent)')

for header in headers:
    print(header)

for cell in cells:
    print(cell)

【讨论】:

    【解决方案2】:

    如果您使用的是 filefox,请转到 about:config 并将 accessibility.blockautorefresh 设置为 true。现在复制您的 Firefox 配置文件...菜单-> 帮助-> 故障排除信息并复制配置文件目录路径。

    在 python 中设置你的 firefox 配置文件

    profile_directory = webdriver.FirefoxProfile("your/copied/path")
    driver = webdriver.Firefox(profile_directory)
    

    对于 chrome,复制 this url 并将其粘贴到 here 并获取 .crx 文件。获得 crx 文件后,在 python 中执行此操作:

    from selenium import webdriver
    from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
    options = webdriver.chrome.options.Options()
    options.add_extension("/path/to/autorefreshblocker.crx")
    capabilities = options.to_capabilities()
    driver = webdriver.chrome(desired_capabilities=capabilities)
    

    【讨论】:

      猜你喜欢
      • 2022-11-26
      • 1970-01-01
      • 2018-02-18
      • 1970-01-01
      • 1970-01-01
      • 2017-03-05
      • 2010-10-01
      • 1970-01-01
      • 2015-02-03
      相关资源
      最近更新 更多