2017-10-05 128 views
2
browser=webdriver.Firefox() 
browser.set_page_load_timeout(4) 
try: 
    browser.get("https://9gag.com") 
except: 
    print("Page took too much time to load") 

当我运行上面的代码,将除执行:块总是和打印“页面花了太多的时间来加载”如何设置页面加载超时新的标签页

但是当我运行下面的代码其中我创建了一个页面,其中有一个带有newPage的按钮,并且一旦它被点击,它就会在新选项卡中打开链接(9gag)。 我没有得到任何exception.It需要完整的时间来加载,然后打印网站

browser=webdriver.Firefox() 
browser.get("file:///F:/documents/html_level_one/link_to_extreme_page_load.html") 
browser.set_page_load_timeout(4) 
browser.find_element_by_id("newPage").click() 
browser.switch_to_window(browser.window_handles[-1]) 
print(browser.current_url) 

我使用的是Firefox 28和硒2.41

my very simple starting page

回答

1

页面加载超时的网址不适用于单击元素,因为Selenium无法知道是否正在加载新页面。这就是没有应用页面加载超时的原因。您可以创建WebDriverWait并等待页面上的元素可见等,并设置超时。

+0

如果我必须在同一页面上使用多个元素,该怎么办? –

+0

只需添加一个等待您正在查找的每个元素。您还可以使用'WebDriverWait'并使用找到多个元素的'expected_conditions',例如'visibility_of_all_elements_located(定位器)'。请参阅[this](http://selenium-python.readthedocs.io/waits.html)和[this](https://seleniumhq.github.io/selenium/docs/api/py/webdriver_support/selenium.webdriver。 support.expected_conditions.html)。 – JeffC

+0

:)我应该必须使用webdriverwait之前单击()或切换到新标签之前或之前打印()? –