有没有办法在 Selenium WebDriver 测试中添加标头? (与 Firefox 修改标头插件一样)我无法使用 HtmlUnitDriver,因为浏览器必须可见。
WebDriver 不允许您使用任何基于浏览器的驱动程序更改或设置标头。您可以在以下 URL 找到有关他们对标头和响应代码的决定的大量信息。 http://code.google.com/p/selenium/issues/detail?id=141
我们使用 Apache HTTP 客户端进行此类测试,我们不想检查呈现的页面元素,而只想检查响应和标头信息。
您还可以为浏览器 mob 代理提供您的 selenium 测试以及上面网址中提到的内容。我已将其用于其他目的,非常棒。
这是一个如何在 Python 中使用 Seleniumwire 的简短示例:
from seleniumwire import webdriver
def set_chrome_driver():
options = webdriver.ChromeOptions()
options.add_argument("--start-maximized")
options.add_argument("--disable-infobars")
options.add_argument("--no-proxy-server")
driver = webdriver.Chrome(executable_path=r'C:\Automation_package\chromedriver.exe')
driver.get('http://172.1.1.1:5000/path/api/')
driver.header_overrides = {"iv-user": "Admin", "iv-groups": "SuperAdmin", "iv-roles": "Viewers",}
driver.get('http://172.1.1.1:5000/path/api/')
还有其他方法可以做到这一点,例如
Browsermob-Proxy
由于
Browsermob-proxy
在我们使用硒网格时有其自身的局限性,以下是我在我的案例中解决问题的方法。希望对具有类似设置的任何人都有帮助。
如何下载Modheader?链接
ChromeOptions options = new ChromeOptions();
options.addExtensions(new File(C://Downloads//modheader//modheader.crx));
// Set the Desired capabilities
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability(ChromeOptions.CAPABILITY, options);
// Instantiate the chrome driver with capabilities
WebDriver driver = new RemoteWebDriver(new URL(YOUR_HUB_URL), options);
.
// set the context on the extension so the localStorage can be accessed
driver.get("chrome-extension://idgpnmonknjnojddfkpgkljpfnnfcklj/_generated_background_page.html");
Where `idgpnmonknjnojddfkpgkljpfnnfcklj` is the value captured from the Step# 2
Javascript
.
((Javascript)driver).executeScript(
"localStorage.setItem('profiles', JSON.stringify([{ title: 'Selenium', hideComment: true, appendMode: '',
headers: [
{enabled: true, name: 'token-1', value: 'value-1', comment: ''},
{enabled: true, name: 'token-2', value: 'value-2', comment: ''}
],
respHeaders: [],
filters: []
}]));");
其中
token-1
、value-1
、token-2
、value-2
是要添加的请求标头和值。
现在导航到所需的 Web 应用程序。
driver.get("your-desired-website");
您可以通过使用 chrome.declarativeNetRequest API 使用远程控制扩展来实现此目的。 由于它不使用任何代理或IO,因此网络速度不会明显降低。
安装:
pip install selenium_injector
示例脚本:
from selenium_injector.webdriver import Chrome
driver = Chrome()
# modify headers
driver.injector.declarativeNetRequest.update_headers({"test": "test_2", "sec-ch-ua-platform": "Android"})
driver.get("https://httpbin.org/headers")
input("press ENTER to exit")
driver.quit()
免责声明:我是 Selenium-Injector 的作者