使用Python的Selenium无法打印console.log消息
我遇到的问题是,当我运行这个Python脚本时,无法在日志中看到任何 console.log、console.error、console.warning 的信息:
import time
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.chrome.options import Options
class ChromeDriver():
def __init__(login_url, user, passwd):
self.login_url = login_url
self.user = user
self.passwd = passwd
def __enter__(self):
options = Options()
options.set_capability('goog:loggingPrefs', {'browser': 'ALL'})
self.driver = webdriver.Chrome(options=options)
self.driver.maximize_window()
self._login()
return self.driver
def _login():
pass # implement login
def __exit__(self, exc_type, exc_val, exc_tb):
self.driver.quit()
def check_console_logs(driver, url):
try:
driver.get(url)
WebDriverWait(driver, 10).until(
EC.presence_of_element_located((By.TAG_NAME, 'title'))
)
if '404' in driver.title:
print(f'failed to open {url}: 404 Not found')
return
logs = driver.get_log('browser')
if logs:
print(f"Console logs found in {url}:")
for log_entry in logs:
print(log_entry['level'], log_entry['message'])
print()
time.sleep(5)
except Exception as ex:
print(f"Error occurred while accessing {url}: {ex}")
test_urls = [''] # add urls to test
with ChromeDriver(username, password) as driver:
for url in test_urls:
check_console_logs(driver, url)
不过,如果我在调试器中暂停程序,然后打开Python启动的浏览器的开发者工具,我就能看到所有的日志。我尝试了很多方法,但仍然无法在Python中记录任何JavaScript的消息。
我只看到一些其他的日志,这些我并不感兴趣,因为我想做的是调用我项目中的不同网址,以查看我的程序流程中是否打印出一些意外的警告或错误。
driver.capabilities 显示浏览器版本是 122.06261.129,chromedriver版本是 122.0.6261.128,我使用的是 selenium 4.18.1 和 Python 3.10。
1 个回答
0
好的,我现在搞明白了,经过深入查看这个链接: https://bugs.chromium.org/p/chromedriver/issues/detail?id=2976
我还需要给驱动程序添加一个服务,并设置 --verbose 这个参数。
from selenium.webdriver.chrome.service import Service
...
def __enter__(self):
...
service = Service(service_args=["--verbose"])
self.driver = webdriver.Chrome(options=options, service=service)
...