使用 Selenium 进行模拟登入和页面内容的获取

原创
2016-07-25 08:46:27 1375浏览

传统的 cURL 无法执行页面中的浏览器脚本,并且在抓取一些对爬虫有限制的网页时,往往要设定详细的 http header 来突破限制,编写起来较为复杂。

Selenium简介:

Selenium 是一个用于Web应用程序测试的工具(用处也不仅仅是测试)。
Selenium 直接使用浏览器运行,像真正的用户在操作。支持较多的浏览器。

组件

Selenium IDE:Firefox插件,有录制脚本的功能。支持自动录制动作和自动生成其他语言的自动化脚本。

Selenium Remote Control (RC) :支持多种平台(Windows,Linux)和多浏览器(IE,Firefox,Opera,Safari,Chrome),可以用多种语言(Java,Ruby,Python,Perl,PHP,C#)编写用例。

Selenium Grid :允许Selenium-RC 针对规模庞大的测试案例集或者需要在不同环境中运行的测试案例集进行扩展。


实例:驱动 chrome 模拟登入淘宝,获取页面信息

1.前往项目主页:SeleniumHQ 下载

Selenium Server (formerly the Selenium RC Server)

Third Party Browser Drivers NOT DEVELOPED by seleniumhq

(选择chrome的driver)

Third Party Language Bindings NOT DEVELOPED by seleniumhq

(选择PHP by Adam Goucher (SeHQ recommended php client))

2.打开 selenium

  1. java -jar path_to_selenium.jar
  2. [-timeout 0]
  3. [-Dwebdriver.server.session.timeout=0]
  4. -Dwebdriver.chrome.driver="path_to_chrome_driver"
  5. -browser [-timeout=0] [-browserTimeout=0]
  6. browserName=chrome,[timeout=0]
复制代码

如需长时间运行请酌情设置各 '[ ]' 中的超时时间

3.php代码

  1. function waitForAjax() {
  2. global $session;
  3. do {
  4. sleep(1);
  5. } while($session->execute(array('script' => "return (document.readyState != 'complete')", 'args' => array())));
  6. } //该函数会把脚本挂起直到等待到Ajax结束
  7. require_once "webdriver/PHPWebDriver/__init__.php";
  8. // 引入 selenium 的PHP封装函数库
  9. // 下载地址:https://github.com/Element-34/php-webdriver
  10. // 文档中有各种操作浏览器方法,如获取所有cookie等
  11. $wd_host = 'http://127.0.0.1:4444/wd/hub';
  12. $web_driver = new PHPWebDriver_WebDriver($wd_host);
  13. $session = $web_driver->session('chrome');
  14. //设置超时时间
  15. $session->implicitlyWait(5);
  16. $session->setScriptTimeout(5);
  17. $session->setPageLoadTimeout(15);
  18. //打开连接
  19. $session->open('http://login.m.taobao.com/login.htm?tpl_redirect_url=http://m.taobao.com');
  20. //输入验证码用,如果需要的话
  21. sleep(5);
  22. //请设置好帐号密码
  23. $session->element('css selector', 'input[name=TPL_username]')->value(array('value' => str_split('your_username')));
  24. $session->element('css selector', 'input[name=TPL_password]')->value(array('value' => str_split('your_password')));
  25. //模拟点击登入按钮
  26. $elements = $session->element('css selector', '.c-btn-oran-big')->click();
  27. //打开 m.taobao.com,此时已获取到cookie
  28. $session->open('http://m.taobao.com/');
  29. //等待ajax加载完毕
  30. waitForAjax();
  31. $elements = $session->element('css selector', 'body')->text();
  32. //获得了登入后ajax执行完毕时的页面内容
  33. ?>
复制代码

之后便可以按需对 $session 实例进行 element 方法的各种操作。

支持以下方式进行选择元素

id xpath link text partial link text name tag name class name css selector
PS:各种库对Ajax情况的检测方法

jQuery: "jQuery.active"

Prototype: "Ajax.activeRequestCount"

Dojo: "dojo.io.XMLHTTPTransport.inFlight.length"

登入, Selenium


声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。
上一条:Redis应用于php,连接mysql的完整案例 下一条:php连接redis的操作库predis操作大全

相关文章

查看更多