使用 Selenium 進行模擬登入和頁面內容的獲取

傳統的 cURL 沒法執行頁面中的瀏覽器腳本,而且在抓取一些對爬蟲有限制的網頁時,每每要設定詳細的 http header 來突破限制,編寫起來較爲複雜。php

Selenium簡介:

Selenium 是一個用於Web應用程序測試的工具(用處也不單單是測試)。
Selenium 直接使用瀏覽器運行,像真正的用戶在操做。支持較多的瀏覽器。css

組件

Selenium IDE:Firefox插件,有錄製腳本的功能。支持自動錄製動做和自動生成其餘語言的自動化腳本。java

Selenium Remote Control (RC) :支持多種平臺(Windows,Linux)和多瀏覽器(IE,Firefox,Opera,Safari,Chrome),能夠用多種語言(Java,Ruby,Python,Perl,PHP,C#)編寫用例。git

Selenium Grid :容許Selenium-RC 針對規模龐大的測試案例集或者須要在不一樣環境中運行的測試案例集進行擴展。github


實例:驅動 chrome 模擬登入淘寶,獲取頁面信息

1.前往項目主頁:SeleniumHQ 下載web

  • Selenium Server (formerly the Selenium RC Server)ajax

  • Third Party Browser Drivers NOT DEVELOPED by seleniumhqchrome

(選擇chrome的driver)瀏覽器

  • Third Party Language Bindings NOT DEVELOPED by seleniumhq

(選擇PHP by Adam Goucher (SeHQ recommended php client))bash

2.打開 selenium

java -jar path_to_selenium.jar 
[-timeout 0] 
[-Dwebdriver.server.session.timeout=0] 
-Dwebdriver.chrome.driver="path_to_chrome_driver"
-browser [-timeout=0] [-browserTimeout=0]
browserName=chrome,[timeout=0]

如需長時間運行請酌情設置各 '[ ]' 中的超時時間

3.PHP代碼

 execute(array('script' => "return (document.readyState != 'complete')", 'args' => array())));
}  //該函數會把腳本掛起直到等待到Ajax結束

require_once "webdriver/PHPWebDriver/__init__.php";
// 引入 selenium 的PHP封裝函數庫
// 下載地址:https://github.com/Element-34/php-webdriver
// 文檔中有各類操做瀏覽器方法,如獲取全部cookie等

$wd_host = 'http://127.0.0.1:4444/wd/hub';
$web_driver = new PHPWebDriver_WebDriver($wd_host);

$session = $web_driver->session('chrome');

//設置超時時間
$session->implicitlyWait(5);
$session->setScriptTimeout(5);
$session->setPageLoadTimeout(15);

//打開鏈接
$session->open('http://login.m.taobao.com/login.htm?tpl_redirect_url=http://m.taobao.com');

//輸入驗證碼用,若是須要的話
sleep(5);

//請設置好賬號密碼
$session->element('css selector', 'input[name=TPL_username]')->value(array('value' => str_split('your_username')));
$session->element('css selector', 'input[name=TPL_password]')->value(array('value' => str_split('your_password')));

//模擬點擊登入按鈕
$elements = $session->element('css selector', '.c-btn-oran-big')->click();

//打開 m.taobao.com,此時已獲取到cookie
$session->open('http://m.taobao.com/');

//等待ajax加載完畢
waitForAjax();

$elements = $session->element('css selector', 'body')->text();
//得到了登入後ajax執行完畢時的頁面內容
?>

以後即可以按需對 $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"

相關文章
相關標籤/搜索