為了獲取網站js渲染后的html,需要利用selenium加載網站,但是會出現加載時間過長的現象,因此可以限制其加載時間以及強制關掉加載:
# !/usr/bin/python3.4
# -*- coding: utf-8 -*-
from selenium.common.exceptions import TimeoutException
from selenium import webdriver
# 打開谷歌瀏覽器
browser = webdriver.Chrome()
# 設定頁面加載限制時間
browser.set_page_load_timeout(10)
# 如果10秒內沒有加載完成就會報錯
# selenium.common.exceptions.TimeoutException: Message: timeout: Timed out receiving message from renderer: 1.684
try:
browser.get('http://www.amazon.com/dp/B001UPMC1Y')
# 打印html
print(browser.page_source)
except TimeoutException:
# 報錯后就強制停止加載
# 這里是js控制
browser.execute_script('window.stop()')
print(browser.page_source)
browser.quit()