Chrome headless 模式

本文介绍如何设置Chrome浏览器的无头(headless)模式进行自动化测试,包括禁用证书错误提示及最大化窗口等设置。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

把自动化测试的运行放在后台:

PhantomJS 非常不错,因为是使用的 QtWebKit 浏览器内核渲染页面,基本可以和真正浏览器保持一致。

Chrome-headless 模式, Google 针对 Chrome 浏览器 59版 新增加的一种模式,可以让你不打开UI界面的情况下使用 Chrome 浏览器,所以运行效果与 Chrome 保持完美一致。PhantomJS作者表示,你这么搞我失业了啊!

话不多叙,直接上代码:

    /**
     * 禁止chrome弹出忽略网站证书错误提示
     * https://github.com/SeleniumHQ/selenium/wiki/ChromeDriver
     * webdriver.chrome.driver
     *
     * @return
     */
    public static ChromeOptions chromeOptions() {
        System.setProperty("webdriver.chrome.driver", "chromedriver");//指定驱动路径
        ChromeOptions options = new ChromeOptions();
        DesiredCapabilities capabilities = DesiredCapabilities.chrome();

        // SSL Certificate
        capabilities.setCapability(CapabilityType.TAKES_SCREENSHOT, true);
        capabilities.setCapability(CapabilityType.SUPPORTS_JAVASCRIPT, true);

        capabilities.setCapability("chrome.switches", Arrays.asList("--start-maximized"));
        // options.addArguments("--headless");
        options.addArguments("--test-type", "--start-maximized");
        options.addArguments("--test-type", "--ignore-certificate-errors");
        options.addArguments("headless");
        return options;
    }
### 如何在 Chrome Headless 模式下处理重定向 当使用 Chrome 浏览器的无头模式Headless Mode)时,可以通过 Puppeteer 或 Selenium WebDriver 来控制浏览器实例并处理页面加载过程中的重定向。 #### 使用 Puppeteer 处理重定向 Puppeteer 是一个 Node.js 库,它提供了一个高级 API 来通过 DevTools 协议控制 Chromium 或 Chrome。下面是一个简单的例子来展示如何捕获和处理重定向: ```javascript const puppeteer = require('puppeteer'); (async () => { const browser = await puppeteer.launch({headless: true}); const page = await browser.newPage(); let response; // 设置请求拦截以便观察每次导航事件 await page.setRequestInterception(true); page.on('request', interceptedRequest => { console.log(`Navigating to ${interceptedRequest.url()}`); interceptedRequest.continue(); }); // 监听响应结束事件以获取最终URL page.on('response', async res => { response = res; console.log(`Final URL after all redirects is ${res.url()}`); }); try { await page.goto('http://example.com/', {waitUntil: 'networkidle2'}); if (response && response.headers().location) { console.log('Redirect occurred'); } else { console.log('No redirect happened.'); } } catch(e){ console.error('Error during navigation:', e.message); } await browser.close(); })(); ``` 这段代码会启动一个新的无头浏览器实例,并尝试访问指定网站 `http://example.com/` 。如果发生任何 HTTP 重定向,则会在日志中记录下来;如果没有发生重定向,则输出相应的消息[^1]。 对于那些希望更深入理解此主题的人士来说,可以进一步探索 Puppeteer 的文档和其他特性,比如设置自定义 User-Agent 字符串、管理 cookies 和 session 数据等。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

AI天才研究院

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值