Skip to content

Instantly share code, notes, and snippets.

@edsion1107
Last active March 27, 2019 09:28
Show Gist options
  • Save edsion1107/c118d2b899a13fbc6a9143955dbb2822 to your computer and use it in GitHub Desktop.
Save edsion1107/c118d2b899a13fbc6a9143955dbb2822 to your computer and use it in GitHub Desktop.
通过webdrvier(chromedriver)检测JS ERROR——页面中有无JS错误。与静态代码检查相比,可以发现运行中的异常。
#!/usr/bin/env python
# encoding: utf-8
"""
@author: edsion
@file: 3.py
@time: 2019-03-26 19:42
"""
import csv
import json
import time
import atexit
import socket
import logging
from pathlib import Path
from selenium import webdriver
from selenium.webdriver.chrome.service import Service as ChromeService
from selenium.common.exceptions import WebDriverException
logger = logging.getLogger(__name__)
capabilities = {
'chromeOptions': {
'androidDeviceSerial': 'a2c0fe65',
'androidPackage': 'com.tencent.mobileqq',
'androidUseRunningApp': True,
'androidProcess': 'com.tencent.mobileqq:tool', # 小游戏主进程
# 'androidProcess': 'com.tencent.mobileqq:mini', # 小程序主进程
}
}
def find_free_port():
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('localhost', 0))
try:
return s.getsockname()[1]
finally:
s.close()
def service_quit(s: ChromeService):
if s:
s.stop()
# chromdriver 2.40 (Supports Chrome v66-68)下载地址:
# https://chromedriver.storage.googleapis.com/2.40/chromedriver_linux64.zip
# https://chromedriver.storage.googleapis.com/2.40/chromedriver_mac64.zip
# https://chromedriver.storage.googleapis.com/2.40/chromedriver_win32.zip
exe_path = Path('../chromedriver').as_posix() # 根据当前环境,替换为chromedriver可执行程序路径(可以是相对路径)
port = find_free_port()
assert port
service = ChromeService(executable_path=exe_path, port=port)
service.start() # 启动 chromedriver
atexit.register(service_quit, service)
error_list = []
try:
driver = webdriver.Remote(command_executor=f'http://127.0.0.1:{port}', desired_capabilities=capabilities)
except WebDriverException as e:
logger.error(f'webdriver初始化失败: {e.msg}')
else:
with open('CDP_log.csv', 'w') as f:
writer = csv.DictWriter(f, ['timestamp', 'source', 'level', 'message'])
writer.writeheader()
for index in range(10): # 调试用,正式使用需要去除循环
time.sleep(1)
print(index)
output = driver.get_log("browser")
for i in output:
# if i.get('source') == 'javascript': # 如果仅判断js的error(还有可能类型是network的)
if i.get('message') not in error_list:
error_list.append(i['message'])
writer.writerow(i)
driver.quit()
# TODO:目前只能监控主进程(单进程),多进程无法同时获取
# TODO: js error的去重问题 —— 目前只能分类,无法计算准确次数
# 结果里的时间戳,是获取log的时间,不是js error发生的时间。如果停留在一个页面上,其实只发生一次但取出来的结果是多次
finally:
if service:
service.stop()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment