【问题标题】:How to use addCustomRequestHeader method in selenium?如何在硒中使用 addCustomRequestHeader 方法?
【发布时间】:2011-08-25 20:29:24
【问题描述】:

我试图使用 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 查找请求标头。这里有人知道我在这里做错了什么吗?任何帮助将不胜感激

【问题讨论】:

  • 它适用于任何自定义标头还是仅支持已知的 HTTP 标头?也就是说,它的行为可能更像一个 addRequestHeader()。
  • 尝试将 Selenium 设置为代理服务器,此处讨论stackoverflow.com/questions/4442405/…

标签: selenium selenium-rc selenium-webdriver


【解决方案1】:

需要在代理注入模式下启动 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 

【讨论】:

    【解决方案2】:

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

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

    这里是代码sn-p

    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 自定义标头快照

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-24
      • 2021-09-29
      • 1970-01-01
      • 2013-09-24
      • 2022-01-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多