Facebook WebDriver:设置用户代理(PHP)

时间:2017-06-23 15:47:23

标签: php facebook selenium webdriver selenium-chromedriver

我正在尝试覆盖用户代理字符串,但到目前为止无法在互联网上找到解决方案......

这是我的剧本:

<?php
namespace Facebook\WebDriver;

use Facebook\WebDriver\Remote\DesiredCapabilities;
use Facebook\WebDriver\Remote\RemoteWebDriver;

require_once('vendor/autoload.php');

$host         = 'http://localhost:4444/wd/hub';
$capabilities = DesiredCapabilities::chrome();
$capabilities->setPlatform(WebDriverPlatform::WINDOWS);
$capabilities->setCapability('userAgent', 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36');
$capabilities->setCapability('user-agent', 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36');
$driver       = RemoteWebDriver::create($host, $capabilities, 5000);

$driver->get('http://localhost/browser-emu/testpage.php?bot=1234');

// wait until the page is loaded
$driver->wait()->until(
    WebDriverExpectedCondition::titleContains('register')
);

echo "User agent: " . $driver->findElement(WebDriverBy::cssSelector('#userAgent'))->getText();

$driver->quit();

页面本身就像:

一样简单
<html>
<body>
<h1>testpage...</h1>

<?php
printf("<div id='userAgent'>%s</div> \n", $_SERVER['HTTP_USER_AGENT']);
?>
</body>
</html>

无论我尝试过什么,总是说用户代理是Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.109 Safari/537.36

有人知道如何覆盖它吗?

我正在使用(在Ubuntu上):

  • facebook / webdriver @ 1.4.1
  • chromedriver @ 2.30.477691

1 个答案:

答案 0 :(得分:6)

我在facebook / web-driver(firefox)official wiki找到了解决方案:

$host = 'http://localhost:4444/wd/hub';

$profile = new FirefoxProfile();
$profile->setPreference('general.useragent.override', 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36');

$caps = DesiredCapabilities::firefox();
$caps->setCapability(FirefoxDriver::PROFILE, $profile);

$driver = RemoteWebDriver::create($host, $caps);

对于Chrome:

$options = new ChromeOptions();
$options->addArguments(array(
    '--user-agent=' . $userAgent
));

$caps = DesiredCapabilities::chrome();
$caps->setCapability(ChromeOptions::CAPABILITY, $options);

$driver = RemoteWebDriver::create($host, $caps);