Part1centos 安装 google-chrome和chromedrive
1下载 Chrome 浏览器的安装包:
wget https://dl.google.com/linux/direct/google-chrome-stable_current_x86_64.rpm
2安装 Chrome 浏览器:
sudo yum localinstall google-chrome-stable_current_x86_64.rpm
3验证 Chrome 是否成功安装:
google-chrome --version
4下载对应版本的 ChromeDriver,并解压到指定目录(/usr/local/bin
):
wget https://chromedriver.storage.googleapis.com/114.0.5735.90/chromedriver_linux64.zip
unzip chromedriver_linux64.zip -d /usr/local/bin/
5启动 ChromeDriver 服务:
LANGUAGE=ZH-CN.UTF-8 /usr/local/bin/chromedriver --port=9515
6成功运行后(不要关闭),您应该会看到类似以下输出:
Starting ChromeDriver {version} on port 9515...
Only local connections are allowed.
Please see https://chromedriver.chromium.org/security-considerations for suggestions on keeping ChromeDriver safe.
ChromeDriver was started successfully.
Part2PHP代码实现
当做完前面两步准备工作,安装好了浏览器(Google Chrome)与浏览器驱动程序(Chromdriver)之后,总算可以进入主题,安装与使用 Php-webdriver 了。我们先再试试看bilibili这个网站,比如:下图的大世界扭蛋机这个标题(图1),我们查看网页源码是没有对应的视频标题的(图2)。
使用composer安装Php-webdriver
写php代码
<?php
require_once('vendor/autoload.php');
use Facebook\WebDriver\Remote\DesiredCapabilities;
use Facebook\WebDriver\Remote\RemoteWebDriver;
use Facebook\WebDriver\Chrome\ChromeOptions;
$options = new ChromeOptions();
$options->addArguments(['--no-sandbox','--headless']);
$capabilities = DesiredCapabilities::chrome();
$capabilities->setCapability(ChromeOptions::CAPABILITY, $options);
$host = 'http://localhost:9555';
$driver = RemoteWebDriver::create($host, $capabilities);
$url = 'https://www.bilibili.com/movie/index/?from_spmid=666.7.index.1#st=2&style_id=10104&area=-1&release_date=-1&season_status=-1&order=2&sort=0&page=1';
// 访问网站
$driver->get($url);
// 获取页面源代码
$pageSource = $driver->getPageSource();
echo $pageSource;
// 关闭 WebDriver 会话
$driver->quit();
运行结果
Part3介绍一下xpath
选择元素: //tagname
:选择所有具有指定标签名称的元素。//tagname[@attribute='value']
:选择具有指定属性值的元素。//tagname[text()='text']
:选择具有指定文本内容的元素。选择父子关系: /parent/child
:选择父节点下的直接子节点。/parent//descendant
:选择父节点下所有后代节点。选择兄弟关系: /preceding-sibling::sibling
:选择当前节点之前的同级节点。/following-sibling::sibling
:选择当前节点之后的同级节点。使用逻辑运算符: and
、or
、not()
:使用逻辑运算符进行条件组合。使用通配符: *
:匹配任意元素。@*
:匹配任意属性。以下是一个使用 XPath 定位元素并执行操作的示例代码:
<?php
$driver = RemoteWebDriver::create($host, $capabilities);
// 打开网页
$driver->get('https://www.example.com/');
// 使用 XPath 定位元素并执行操作
$element = $driver->findElement(WebDriverBy::xpath("//input[@name='username']"));
$element->sendKeys('admin');
// 关闭 WebDriver 连接
$driver->quit();
$driver->findElement()
方法和 WebDriverBy::xpath()
来通过 XPath 表达式定位页面上的元素。在示例中,我们使用了 //input[@name='username']
的 XPath 表达式来选择具有 name
属性值为 'username'
的 <input>
元素。然后,我们使用 $element->sendKeys()
方法向选定的元素发送键盘输入。
评论 (0)