如何在selenium中使用addCustomRequestHeader方法?

时间:2011-08-25 20:29:25

标签: selenium selenium-rc selenium-webdriver

我尝试使用addCustomRequestHeader方法为selenium请求设置自定义标头。以下是源代码

       Selenium sel = new DefaultSelenium("localhost",4444,"*firefox","http://www.google.com");
       sel.start("addCustomRequestHeader=true");
//  sel.start();
    sel.addCustomRequestHeader("mycustomheader","automation");
    sel.open("http://www.google.com/");

此代码未将标头添加到请求中。我试图使用Fiddler查找请求标头。这里有谁知道我在这里做错了什么?任何帮助将不胜感激

2 个答案:

答案 0 :(得分:2)

您需要以代理注入模式启动selenium

java -jar selenium-server-standalone.jar -proxyInjectionMode

然后,您可以添加这样的自定义请求标头(在Python中)

sel.start("addCustomRequestHeader=true")
sel.add_custom_request_header("mycustomheader","automation")
sel.open('http://www.google.com')

要查看是否已应用自定义标头,请检查运行selenium服务器的选项卡。您应该在控制台消息中看到类似的内容

INFO - Command request: addCustomRequestHeader[mycustomheader, automation] on session 
INFO - Got result: OK on session 

答案 1 :(得分:1)

在我的情况下,以代理注入模式运行selenium是不可接受的,因此我遵循了'ModHeader'chrome扩展名的方法来设置自定义标头。这种方法对我来说很好。

ModHeader Extension: https://github.com/mdamien/chrome-extensions-archive

这是代码段

ChromeOptions chromeOpt = new ChromeOptions();
chromeOpt.addArguments("--no-sandbox");
System.setProperty("webdriver.chrome.args", "--disable-logging");
System.setProperty("webdriver.chrome.silentOutput", "true");

chromeOpt.addExtensions(new File("./ModHeader_v2.2.3.crx"));

WebDriver driver = new ChromeDriver(chromeOpt);

// set the context on the extension so the localStorage can be accessed
driver.get("chrome-extension://idgpnmonknjnojddfkpgkljpfnnfcklj/icon.png");

// setup ModHeader with two headers (token1 and token2)
((JavascriptExecutor)driver).executeScript(
"localStorage.setItem('profiles', JSON.stringify([{                " +
"  title: 'Selenium', hideComment: true, appendMode: '',           " +
"  headers: [                                                      " +
"    {enabled: true, name: 'token1', value: 'testHeaderValue1', comment: ''}, " +
"    {enabled: true, name: 'token2', value: 'testHeaderValue2', comment: ''}  " +
"  ],                                                              " +
"  respHeaders: [],                                                " +
"  filters: []                                                     " +
"}]));                                                             ");
driver.navigate().to("https://localhost:8443");

Fiddler自定义标头快照 Fiddler Custom header snapshot