以下为详细解释,如果您觉得过长,请看TLDR:
当前版本的Selenium Ghostdriver(在PhantomJS 1.9.8中)忽略了resourceTimeout选项,使用webdriver的implicitly_wait()、set_page_load_timeout()方法,并将它们包装在try-except块中。
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:
print(e)
finally:
browser.quit()
说明
为了将PhantomJS页面设置提供给Selenium,可以使用webdriver的DesiredCapabilities,例如:
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)
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将不会应用resourceTimeout(请参见Github上的Ghostdriver问题#380)。
为了解决这个问题,只需使用Selenium的超时函数/方法,并将webdriver的get方法包装在try-except / try-catch块中,例如:
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:
print(e)
finally:
browser.quit()
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) {
System.out.println(e.getMessage());
} finally {
webdriver.quit();
}