使用phantomjs進行網頁抓取的實現代碼_javascript技巧

來源:互聯網
上載者:User

phantomjs因為是無頭瀏覽器可以跑js,所以同樣可以跑dom節點,用來進行網頁抓取是再好不過了。

比如我們要批量抓取網頁 “曆史上的今天” 的內容。網站

對dom結構的觀察發現,我們只需要取到 .list li a的title值即可。因此我們利用進階選取器構建dom片段

var d= ''var c = document.querySelectorAll('.list li a')var l = c.length;for(var i =0;i<l;i++){d=d+c[i].title+'\n'}

之後只需要讓js代碼在phantomjs裡跑起來即可~

var page = require('webpage').create();page.open('http://www.todayonhistory.com/', function (status) { //開啟頁面if (status !== 'success') {console.log('FAIL to load the address');} else {console.log(page.evaluate(function () {var d= ''var c = document.querySelectorAll('.list li a')var l = c.length;for(var i =0;i<l;i++){d=d+c[i].title+'\n'}return d}))}phantom.exit();});

最終我們另存新檔catch.js,在dos裡面執行一下,輸出內容到txt檔案(也可以用phantomjs的檔案api來寫)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.