在ubuntu服务器中安装 webdriver chrome 的方法可参考:https://blog.qqvbc.com/default/637.html

安装后执行(默认端口是9515):

#如果和PHP服务器不在一个机器上,需要加上allowed-ips参数,允许远程IP访问本地端口
chromedriver [--allowed-ips=192.168.8.29]

PHP使用composer安装php-webdriver/webdriver库文件:

以下是PHP代码调用服务器运行的webdriver服务端口在服务器中渲染网页,并截图的代码:

require_once 'autoload.php';

use Facebook\WebDriver\Chrome\ChromeOptions;
use Facebook\WebDriver\Remote\DesiredCapabilities;
use Facebook\WebDriver\Remote\RemoteWebDriver;
...
public function actionTest($text=null)
    {
        $capabilities = DesiredCapabilities::chrome();
        $host = 'http://127.0.0.1:9515';
        $options = new ChromeOptions();
        $options->addArguments(
            [
                  '--no-sandbox',                        // 解决DevToolsActivePort文件不存在的报错
                 'window-size=1920x1080',               // 指定浏览器分辨率
                //   '--disable-gpu',                       // 谷歌文档提到需要加上这个属性来规避bug
                //   '--hide-scrollbars',                   // 隐藏滚动条, 应对一些特殊页面
                //  'blink-settings=imagesEnabled=false',  // 不加载图片, 提升速度
                // '--ignore-certificate-errors',
                // '--ignore-ssl-errors',
                '--headless',                          // 浏览器不提供可视化页面
            ]
        );
        $options->setExperimentalOption('useAutomationExtension',false);
        $options->setExperimentalOption('excludeSwitches', ['enable-automation', 'enable-logging']);
        $capabilities->setCapability(ChromeOptions::CAPABILITY, $options);

        $driver = RemoteWebDriver::create($host, $capabilities);
        $driver->get('https://www.baidu.com/');
        $title = $driver->getTitle();
        $content = $driver->getPageSource();
        $driver->takeScreenshot('test.png');
        var_dump($title);
}


    /**
     * 获取页面中的一个元素
     * @param RemoteWebDriver $driver
     * @param WebDriverBy $query
     * @param int $timeout
     * @return RemoteWebElement|null
     */
    public static function getElement(RemoteWebDriver $driver, WebDriverBy $query, int $timeout=30)
    {
        while ($timeout>0) {
            try {
                return $driver->findElement($query);
            } catch (\Exception $e) {
                $timeout--;
                sleep(1);
            }
        }
        return null;
    }


        //上传input控件
        $query = WebDriverBy::cssSelector('#app > div > div > div.upload-container > div.video-uploader-container.upload-area > div.upload-wrapper > div > input');
        //上传多个文件
        if ($el = Account::getElement($this->driver, $query)) {
            //sendKeys方法用于向输入控件输入文字,也可用于向文件控件指定要上传的文件路径,可上传多个文件的控件可使用换行来分隔文件列表
            $el->sendKeys(implode("\n", $fileList));
        }
....

截图后发现图片上的中文字体没有正常显示,而是一些方框,是因为服务器系统中没有中文字体的原因
在WIN系统中找一些中文字体上传到服务器 /usr/share/fonts/ 中执行如下命令后,即可解决

 mv msyh*.ttc /usr/share/fonts/
 mkfontscale 
 mkfontdir 
 fc-cache -fv

通过在服务器安装webdriver + chrome,可以实现很多功能,模拟人为操作

标签: none

添加新评论