我的问题是,当我运行此 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 消息。
我只看到一些其他日志,我对此不感兴趣,因为我想做的是调用我的项目的不同url,以查看我的程序流程中是否打印了一些意外的警告或错误。
driver.capability显示browserVersion 122.06261.129,chromedriverVersion是122.0.6261.128,我使用selenium 4.18.1和Python 3.10。
好吧,在深入研究此链接后我现在明白了: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)
...