温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

selenium部署

发布时间:2020-08-11 19:47:33 来源:网络 阅读:334 作者:Lee_吉 栏目:web开发
  1. 安装selenium:
    composer  require  facebook/webdriver
  2. 下载jdk(略)
  3. 下载selenium服务:
    https://goo.gl/FCSwwD
  4. 运行selenium服务:
    java  -jar  selenium-server-standalone-3.14.0.jar
  5. 下载chromedriver:
    https://chromedriver.storage.googleapis.com/2.9/chromedriver_win32.zip
  6. 将chromedriver放到chrome安装目录下:
    C:\Program Files (x86)\Google\Chrome\Application
  7. 移动chromedriver到chrome安装目录:
    selenium部署
  8. 添加chrome安装目录下环境变量:
    selenium部署
  9. 编写测试代码(test.php):

    <?php
    namespace Facebook\WebDriver;
    use Facebook\WebDriver\Remote\DesiredCapabilities;
    use Facebook\WebDriver\Remote\RemoteWebDriver;
    require_once('vendor/autoload.php');
    header("Content-Type: text/html; charset=UTF-8");
    $waitSeconds = 15;  //需等待加载的时间,一般加载时间在0-15秒,如果超过15秒,报错。
    $host = 'http://localhost:4444/wd/hub'; // this is the default
    $capabilities = DesiredCapabilities::chrome();
    $driver = RemoteWebDriver::create($host, $capabilities, 5000);
    $baseUrl = 'http://www.bilibili.com/';
    $driver->get($baseUrl);
    echo consoleText($driver->getTitle()) . "\n";    //cmd.exe中文乱码,所以需转码
    $topLists = $driver->findElement(WebDriverBy::className('container-top-wrapper'))->findElement(WebDriverBy::className('top-list-wrapper'))->findElements(WebDriverBy::tagName('li'));
    foreach ($topLists as $topLi) {
    $itemContent = $topLi->findElement(WebDriverBy::tagName('a'));
    echo consoleText($itemContent->getAttribute('title')) . ' : ' . consoleText($itemContent->getAttribute('href')) . "\n";
    }
    //关闭浏览器
    $driver->quit();
    function consoleText($text, $pageEncoding = '', $consoleEncoding = '')
    {
    // windows
    if (!$consoleEncoding) {
        if (stristr(php_uname('s'), 'win')) {
            $consoleEncoding = "GBK";
        } else {
            $consoleEncoding = 'UTF-8';
        }
    }
    return exchangeEncoding($text, $pageEncoding, $consoleEncoding);
    }
    function exchangeEncoding($text, $pageEncoding = '', $targetEncoding = 'UTF-8')
    {
    if (!$pageEncoding) {
        $pageEncoding = mb_detect_encoding($text, array("ASCII", 'UTF-8', "GB2312", "GBK", 'BIG5'));
    }
    
    if ($pageEncoding != $targetEncoding) {
        return mb_convert_encoding($text,$targetEncoding,$pageEncoding);
    }
    
    return $text;
    }
    //切换至最后一个window
    function switchToEndWindow($driver)
    {
    
    $arr = $driver->getWindowHandles();
    foreach ($arr as $k => $v) {
        if ($k == (count($arr) - 1)) {
            $driver->switchTo()->window($v);
        }
    }
    }
  10. 运行测试代码:
    php  test.php

    selenium部署

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI