使用chromedriver以编程方式启用chrome中的“保留日志”

时间:2016-11-21 17:41:35

标签: selenium-webdriver google-chrome-devtools selenium-chromedriver

如何为chrome开发人员设置启用保留日志选项 - >偏好设置 - >使用chromeoptions.add_argument或通过将Desf添加到DesiredCapabilities或以编程方式的任何其他方式保留登录导航。

1 个答案:

答案 0 :(得分:2)

您可以从performance日志获取重定向。根据{{​​3}}和docs,这是我在C#中所做的,应该可以在Python中移植:

var options = new ChromeOptions();
var cap = DesiredCapabilities.Chrome();
var perfLogPrefs = new ChromePerformanceLoggingPreferences();
perfLogPrefs.AddTracingCategories(new string[] { "devtools.network" });
options.PerformanceLoggingPreferences = perfLogPrefs;
options.AddAdditionalCapability(CapabilityType.EnableProfiling, true, true);
ptions.SetLoggingPreference("performance", LogLevel.All);
var driver = new ChromeDriver(options);
var url = "https://some-website-that-will-redirect.com/";
driver.Navigate().GoToUrl(url);
var logs = driver.Manage().Logs.GetLog("performance"); //all your logs with redirects will be here

循环显示logs,如果message.params.redirectResponse.url等于原始网址,则message.params.request.url将包含重定向网址

Node.JS使用webdriverio

var options = {
    desiredCapabilities: {
        browserName: 'chrome',
        loggingPrefs: {
            'browser': 'ALL',
            'driver': 'ALL',
            'performance': 'ALL'
        },
        chromeOptions: {
            perfLoggingPrefs: {
                traceCategories: 'performance'
            },
        }
    }
var client = webdriverio.remote(options);
await client.url(url);
var logs = await client.log('performance');
var navigations = parseLogs(logs, url);

function parseLogs(logs, url) {
    var redirectList = [];
    while (true) {
        var targetLog = (logs.value.find(l => {
            if (l.message.indexOf(url) == -1)
                return false;
            var rootMessage = JSON.parse(l.message);
            if (((((rootMessage || {}).message || {}).params || {}).redirectResponse || {}).url == url)
                return true;
            return false;
        }) || {}).message;
        if (!targetLog)
            break;
        if (redirectList.indexOf(url) != -1)
            break;
        redirectList.push(url);
        var targetLogObj = JSON.parse(targetLog);
        var nextUrl = ((((targetLogObj || {}).message || {}).params || {}).request || {}).url;

        if (nextUrl) {
            url = nextUrl;
            continue;
        }
        break;
    }
    return redirectList;
}