简体   繁体   中英

selenium webdriver takes too long to load a page

I use PhantomJS as my webdriver. Sometimes it takes too long to load a webpage but I don't know why

import time
from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities

dcap = dict(DesiredCapabilities.PHANTOMJS)
dcap["phantomjs.page.settings.userAgent"] = 'Mozilla/5.0 (Windows NT 10.0;  WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.80 Safari/537.36'
driver = webdriver.PhantomJS(service_args=['--load-images=no'], desired_capabilities=dcap)
t=time.time()
driver.get('http://www.tibetculture.net/2012zyzy/zx/201509/t20150915_3939844.html')
print 'Time consuming:', time.time() - t

It took about 86s to load the page. In a browser, the webpage can be loaded in several seconds and I have no idea why webdriver PhantomJS takes such a long time. What's wrong with it?

There is a "pending" script running continuously. What I would do is to set the page load timeout , handle the TimeoutException by issuing window.stop() :

from selenium.common.exceptions import TimeoutException

t = time.time()
driver.set_page_load_timeout(10)

try:
    driver.get('http://www.tibetculture.net/2012zyzy/zx/201509/t20150915_3939844.html')
except TimeoutException:
    driver.execute_script("window.stop();")
print('Time consuming:', time.time() - t)

print(driver.find_element_by_id("NewsTitle").text)

Prints the news title (proving that you can now locate elements and make actions on the page):

Time consuming: 10.590633869171143
让藏医药走出雪域高原

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM