如何改变selenium webdriver nodejs land中的selenium用户代理?

我在JavaScript +摩卡+节点土地。

我曾尝试将userAgent和“user-agent”设置为function上的键:

var webdriver = require('selenium-webdriver'); var ua = 'Mozilla/5.0 (iPhone; CPU iPhone OS 5_0 like Mac OS X)'; var driver = new webdriver.Builder(). ... withCapabilities({ 'browserName': 'firefox', userAgent: ua, 'user-agent': ua, }). build(); 

有这个答案 ,说使用Firefox的configuration文件,但没有暴露。 没有driver.FirefoxProfile也没有一个暴露在全球范围内, webdriver.FirefoxProfile也没有driver.profiles

我试过谷歌search,看源和文档,但没有什么关于此。

我用这个代码成功地改变了幻影的用户代理:

 var capabilities = { 'browserName': 'phantomjs', 'phantomjs.page.settings.userAgent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1847.11 Safari/537.36' }; return browser .init(capabilities) ... 

此链接显示如何更改Firefox的用户代理,尽pipe提供的代码是C#/ Ruby。

你只需要安装firefox-profile包。 这是一个片段:

 var webdriver = require('selenium-webdriver'); var FirefoxProfile = require('firefox-profile'); var myProfile = new FirefoxProfile(); var capabilities = webdriver.Capabilities.firefox(); // here you set the user-agent preference myProfile.setPreference('general.useragent.override', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1847.131 Safari/537.36'); // attach your newly created profile myProfile.encoded(function(encodedProfile) { capabilities.set('firefox_profile', encodedProfile); // start the browser var wd = new webdriver.Builder(). withCapabilities(capabilities). build(); wd.get('http://testingsite.com/'); }); 

十分简单!

不能用Firefox做,但你可以用Chrome做。 这是无证的:

 var chrome = require('selenium-webdriver/chrome'); var opts = new chrome.Options(); opts.addArguments(['user-agent="YOUR_USER_AGENT"']); var driver = new webdriver.Builder(). withCapabilities(opts.toCapabilities()). build(); 

对于铬你可能会这样做:

 var driver = new webdriver.Builder() .usingServer('http://localhost:4444/wd/hub') .withCapabilities({browserName: 'chrome', chromeOptions: {args:['user-agent="Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36"'] } }) .build();