python - selenium webdriver 加载页面的时间太长

标签 python selenium webdriver phantomjs onload

我使用 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 需要这么长时间。有什么问题吗?

最佳答案

有一个“挂起”的脚本持续运行。我要做的是设置页面加载超时,通过发出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
让藏医药走出雪域高原

关于python - selenium webdriver 加载页面的时间太长,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36299228/

相关文章:

python - 从 python 脚本中获取 Flattr 交易?

java - Selenium 使用太多内存

python - 在 Selenium 中使用 find_element_by_class_name 遍历多个类

python - 如何对字典进行排序?

python - sqlalchemy 无法删除表

linux - headless Protractor 测试不插入 Xvfb

selenium - 如何使用 Selenium 处理 IE [Windows 10] 中弹出的 Windows Security

java - 无法单击 www.mail.com/int/using Selenium WebDriver 中的“撰写”按钮

python - 获取命名日志级别的列表

testing - 如何将 Sikuli 脚本导入 Selenium?