selenium webdriver加载pag所需的时间太长

2024-04-28 15:02:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用PhantomJS作为我的网络驱动程序。有时网页加载时间太长,但我不知道为什么

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

大约用了86秒才装上这一页。在浏览器中,网页可以在几秒钟内加载,我不知道为什么webdriver PhantomJS要花这么长时间。怎么了?


Tags: fromimport网络网页timedriverselenium驱动程序
1条回答
网友
1楼 · 发布于 2024-04-28 15:02:21

有一个“挂起”脚本正在持续运行。我要做的是设置页面加载超时,通过发出window.stop()来处理TimeoutException

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)

打印新闻标题(证明您现在可以在页面上定位元素并执行操作):

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

相关问题 更多 >