下面有长解释,所以TLDR:
当前版本的 Selenium 的 Ghostdriver(在 PhantomJS 1.9.8 中)忽略了 resourcesTimeout 选项,使用 webdriver 的implicitly_wait()、set_page_load_timeout() 并将它们包装在 try- except 块下。
#Python
from selenium import webdriver
from selenium.common.exceptions import TimeoutException
browser = webdriver.PhantomJS()
browser.implicitly_wait(3)
browser.set_page_load_timeout(3)
try:
browser.get("http://url_here")
except TimeoutException as e:
#Handle your exception here
print(e)
finally:
browser.quit()
解释
提供PhantomJS页面设置对于 Selenium,可以使用 webdriver 的 DesiredCapability,例如:
#Python
from selenium import webdriver
cap = webdriver.DesiredCapabilities.PHANTOMJS
cap["phantomjs.page.settings.resourceTimeout"] = 1000
cap["phantomjs.page.settings.loadImages"] = False
cap["phantomjs.page.settings.userAgent"] = "faking it"
browser = webdriver.PhantomJS(desired_capabilities=cap)
//Java
DesiredCapabilities capabilities = DesiredCapabilities.phantomjs();
capabilities.setCapability("phantomjs.page.settings.resourceTimeout", 1000);
capabilities.setCapability("phantomjs.page.settings.loadImages", false);
capabilities.setCapability("phantomjs.page.settings.userAgent", "faking it");
WebDriver webdriver = new PhantomJSDriver(capabilities);
但是,这里有一个问题:就像今天(2014 年 12 月 11 日)使用 PhantomJS 1.9.8 及其嵌入式 Ghostdriver 一样,Ghostdriver 不会应用资源超时(请参阅 Github 中的 Ghostdriver 问题#380).
对于解决方法,只需使用 Selenium 的超时函数/方法并将 webdriver 的 get 方法包装在 try- except/try-catch 块中,例如
#Python
from selenium import webdriver
from selenium.common.exceptions import TimeoutException
browser = webdriver.PhantomJS()
browser.implicitly_wait(3)
browser.set_page_load_timeout(3)
try:
browser.get("http://url_here")
except TimeoutException as e:
#Handle your exception here
print(e)
finally:
browser.quit()
//Java
WebDriver webdriver = new PhantomJSDriver();
webdriver.manage().timeouts()
.pageLoadTimeout(3, TimeUnit.SECONDS)
.implicitlyWait(3, TimeUnit.SECONDS);
try {
webdriver.get("http://url_here");
} catch (org.openqa.selenium.TimeoutException e) {
//Handle your exception here
System.out.println(e.getMessage());
} finally {
webdriver.quit();
}