seleniumでエラー探し
やりたいこと
サイトを修正した際に、今までのページにエラーが起きてないかを確認したかった。
しかしながら、自動テストが開発環境上できなかったので、とりあえずseleniumで、エラーが出てるページがないか探すようにした。
環境
python 3.6.0
mac
プログラム
pageCheck.py
import urllib.request
import ssl
from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
chrome_options = webdriver.ChromeOptions()
prefs = {"profile.default_content_setting_values.notifications" : 2}
chrome_options.add_experimental_option("prefs",prefs)
# エミュレーション利用時はこちらをコメントアウト
# mobile_emulation = { "deviceName": "Nexus 7" }
# chrome_options.add_experimental_option("mobileEmulation", mobile_emulation)
# こちらでLogTypeとか設定します。
# https://github.com/SeleniumHQ/selenium/wiki/Logging
caps = DesiredCapabilities.CHROME
caps['loggingPrefs'] = {'browser': 'SEVERE'}
driver = webdriver.Chrome(chrome_options=chrome_options, desired_capabilities=caps)
# HTTPS対応
ssl._create_default_https_context = ssl._create_unverified_context
# ここにチェックしたいURLを記載してください。
urls = [
'https://www.google.co.jp/'
]
for url in urls:
# レスポンスコードを取得
req = urllib.request.Request(url)
try:
urllib.request.urlopen(req)
except urllib.error.HTTPError as e:
print(url, 'HTTP Response Error', e.code)
continue
# JSエラーを取得
driver.get(url)
for entry in driver.get_log('browser'):
print(url, entry['message'])
driver.close();
requirements.txt
certifi==2017.7.27.1
chardet==3.0.4
get==0.0.21
idna==2.6
post==0.0.13
public==0.0.38
query-string==0.0.12
request==0.0.13
requests==2.18.4
selenium==3.5.0
setupfiles==0.0.50
urllib3==1.22
メモ
スクロールしてデザインの目視確認したい時用
pageScroll.py
import ssl
from selenium import webdriver
from time import sleep
chrome_options = webdriver.ChromeOptions()
prefs = {"profile.default_content_setting_values.notifications" : 2}
chrome_options.add_experimental_option("prefs",prefs)
driver = webdriver.Chrome(chrome_options=chrome_options)
ssl._create_default_https_context = ssl._create_unverified_context
urls = [
'https://www.yahoo.co.jp/'
]
for url in urls:
driver.get(url)
SCROLL_PAUSE_TIME = 0.1
new_height = 0
scroll_once = 200
last_height = driver.execute_script("return document.body.scrollHeight") - scroll_once
while True:
next_height = new_height + scroll_once
# Scroll down to bottom
driver.execute_script("window.scrollTo(" + str(new_height) + ", " + str(next_height) + ");")
# Wait to load page
sleep(SCROLL_PAUSE_TIME)
if new_height > last_height:
break
new_height = next_height
driver.close()
参考
https://watirmelon.blog/2016/06/29/using-webdriver-to-automatically-check-for-javascript-errors-on-every-page-2016-edition/
https://stackoverflow.com/questions/20986631/how-can-i-scroll-a-web-page-using-selenium-webdriver-in-python