3

以前我一直在使用 chrome Auto Refresh 插件。但是,现在我的代码有多个 ChromeDriver 实例打开和关闭,我无法使用 Auto Refresh。此外,在新计算机上安装 Auto Refresh 也很麻烦。

有没有办法用类似于谷歌自动刷新的 Selenium 来刷新驱动程序(模拟 F5 说每 15 秒如果驱动程序不改变保持不动)?

4

3 回答 3

9

refresh 是一个内置命令。

driver = webdriver.Chrome()
driver.get("http://www.google.com")
driver.refresh()

如果您没有 chrome 驱动程序,可以在这里找到: https ://code.google.com/p/chromedriver/downloads/list

将二进制文件放在与您正在编写的 python 脚本相同的文件夹中。(或将其添加到路径或其他任何内容,更多信息:https ://code.google.com/p/selenium/wiki/ChromeDriver )

编辑:

如果你想每 10 秒刷新一次,只需用循环和延迟包装刷新行。例如:

import time
while(True):
    driver.refresh()
    time.sleep(refresh_time_in_seconds)

如果您只想在页面未更改的情况下刷新,请跟踪您所在的页面。driver.current_url是当前页面的 url。因此,将它们放在一起它将是:

import time
refresh_time_in_seconds = 15
driver = webdriver.Chrome()
driver.get("http://www.google.com")
url = driver.current_url
while(True):
    if url == driver.current_url:
        driver.refresh()
    url = driver.current_url
    time.sleep(refresh_time_in_seconds)
于 2013-07-21T06:00:03.813 回答
3

那么有两种方法可以做到这一点。1.我们可以使用刷新方法

driver.get("某个网站的网址"); driver.navigate().refresh();

  1. 我们可以使用动作类并模仿 F5 按下

    动作动作 = 新动作(驱动程序);act.SendKeys(Keys.F5).perform();

于 2013-07-21T06:15:04.153 回答
1

如果您编写必须运行的单元测试,就像每次都必须打开/刷新新的浏览器会话一样,您可以使用带有 before 注释的方法:

@Before
public void refreshPage() {
    driver.navigate().refresh();
}

If all tests are individually successful (green) but fail all together, the reason might also been that you need to wait for some resources to be available on the page, so you also need to handle it, setting the timeout like this:

public WebElement getSaveButton() {
    return findDynamicElementByXPath(By.xpath("//*[@id=\"form:btnSave\"]"), 320);
}

320 is a long time, but you must make sure that you give enough time to get all that it takes to test.

于 2014-03-17T09:17:31.073 回答