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
让藏医药走出雪域高原