使用 python 和 selenium 抓取 chrome 浏览器的控制台日志输出

问题描述 投票:0回答:1

标题确实概括了这一点。我对将 selenium 与 python 一起使用完全陌生。使用 python 脚本,我尝试在网站的控制台上运行命令,然后尝试检索该命令的输出以供我的 python 脚本使用。

from selenium import webdriver
from selenium.webdriver.common.by import By

chromedriver = "path to driver"
driver = webdriver.Chrome(executable_path=chromedriver)

# load some site
driver.get('http://example.com') #orignally I used foo.com but stackoverflow doesn't like that

driver.execute_script("console.log('hello world')")
# print messages
for entry in driver.get_log('browser'):
    print(entry)

但这不会返回任何东西

在打开的页面上执行检查元素并转到控制台。我看到我的 hello world 消息确实在那里。

enter image description here

但我不知道为什么我的代码没有返回它。任何帮助将不胜感激,谢谢!

python google-chrome selenium-webdriver selenium-chromedriver webdriver
1个回答
1
投票

以下是如何保存控制台日志并打印出来:

from selenium import webdriver

driver = webdriver.Chrome()

driver.execute_script("""
    console.stdlog = console.log.bind(console);
    console.logs = [];
    console.log = function(){
        console.logs.push(Array.from(arguments));
        console.stdlog.apply(console, arguments);
    }
    """)

driver.execute_script("console.log('hello world ABC')")
driver.execute_script("console.log('hello world 123')")

print(driver.execute_script("return console.logs"))

driver.quit()

这是其输出:

[['hello world ABC'], ['hello world 123']]
© www.soinside.com 2019 - 2024. All rights reserved.