天天看點

爬蟲入門五(Phantomjs和selenium)1.Phantomjs2.selenium3.pyquery4.總結:

1.Phantomjs

1.簡介:

PhantomJS是一個無界面的,可腳本程式設計的WebKit浏覽器引擎。它原生支援多種web 标準:DOM 操作,CSS選擇器,JSON,Canvas 以及SVG。

2.必須掌握的操作:

官方文檔:http://phantomjs.org/quick-start.html

console.log('輸出');#顯示
phantom.quit();#停止
#頁面加載并下載下傳這個圖檔
var page = require('webpage').create();
page.open('http://cuiqingcai.com', function (status) {
    console.log("Status: " + status);
    if (status === "success") {
        page.render('example.png');
    }
    phantom.exit();
});#函數功能自己推測一下喽
#evaluate 利用 evaluate 方法我們可以擷取網頁的源代碼。這個執行是“沙盒式”的,它不會去執行網頁外的 JavaScript 代碼。evalute 方法可以傳回一個對象,然而傳回值僅限于對象,不能包含函數(或閉包)(感覺很重要)
#打開百度網頁的console,可以看到一堆資訊,evaluate卻隻傳回一個對象。任何來自于網頁并且包括來自 evaluate() 内部代碼的控制台資訊,預設不會顯示。可以重寫函數。
var url = 'http://www.baidu.com';
var page = require('webpage').create();
page.open(url, function(status) {
  var title = page.evaluate(function() {
    return document.title;
  });
  console.log('Page title is ' + title);
  phantom.exit();
});

#重寫的函數
page.onConsoleMessage = function (msg) {
    console.log(msg);
};


#捕獲目前頁面,還可以設定大小
 page.render('github.png');
           

2.selenium

1.簡介:

一種測試工具來驗證浏覽器頁面的行為

2.功能:

#支援多種擷取對象方式,填充文本框。<input type="text" name="passwd" id="passwd-id" />

element = driver.find_element_by_id("passwd-id")
element = driver.find_element_by_name("passwd")
element = driver.find_elements_by_tag_name("input")
element = driver.find_element_by_xpath("//input[@id='passwd-id']")
#傳送内容以及操作
element.send_keys('text',keys.ARROW_DOWN)
#每次傳送的内容不會消失
element.clear()
#填充下拉框
from selenium.webdriver.support.ui import  Select
select=Select(driver.find_element_by_name('name'))
select.select_by_index()
select.select_by_value()
select.select_by_visible_text()
#獲得已選選項
all_selected_options = select.all_selected_options
select.options()
#送出某個元素
element.submit()
driver.find_element_by_id('submit').click()
           

現在的網頁越來越多采用了 Ajax 技術,這樣程式便不能确定何時某個元素完全加載出來了。這會讓元素定位困難而且會提高産生 ElementNotVisibleException 的機率。

是以 Selenium 提供了兩種等待方式,一種是隐式等待,一種是顯式等待。

顯式等待
顯式等待指定某個條件,然後設定最長等待時間。如果在這個時間還沒有找到元素,那麼便會抛出異常了

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

driver = webdriver.Chrome()
driver.get("http://somedomain/url_that_delays_loading")
try:
    element = WebDriverWait(driver, ).until(
        EC.presence_of_element_located((By.ID, "myDynamicElement"))
   #這個地方有多種API選擇
    )
finally:
    driver.quit()
           

3.pyquery

1.簡介:

python裡模仿jquery的操作,文法一緻。jQuery?一套js的庫,操作更加簡單了。

2.小操作:

#初始化,4種,傳代碼,傳位址,傳檔案,lxml.etree。
doc=pq('')
#屬性操作:
li=doc('li')#獲得所有<li 内容
type(li)#輸出pquery,可以繼續篩選,而不是之前的正則傳回的清單。
doc.attr('id')#獲得id的值
doc.attr('id','anothername')#id 換成另一個名字
li.removeclass('')
li.addclass('')
#dom操作
li.append('content')
li.preappend()#加在内容前,上面内容後。

           

4.總結:

略微了解了js,jquery。小功能的大緻了解。。用的時候再看文檔。

17/9/12