1.新建工程
打开PhpStorm新建工程如下:
打开终端输入如下命令安装selenium:
composer require php-webdriver/webdriver
2.编写代码
<?php
require 'vendor/autoload.php';
use Facebook\WebDriver\Remote\RemoteWebDriver;
use Facebook\WebDriver\Remote\DesiredCapabilities;
use Facebook\WebDriver\WebDriverBy;
class BaiduTest
{
public function runTest()
{
$serverUrl = 'http://localhost:4444';
$driver = RemoteWebDriver::create($serverUrl, DesiredCapabilities::chrome());
sleep(3);
try {
$driver->get('https://www.baidu.com');
$searchBox = $driver->findElement(WebDriverBy::id('kw'));
$searchBox->sendKeys('Hello');
sleep(2);
$searchButton = $driver->findElement(WebDriverBy::id("su"));
$searchButton->click();
} finally {
$driver->quit();
}
}
}
$test = new BaiduTest();
$test->runTest();
运行之前先开启一个终端执行:
chromedriver --port=4444