Python基础6 爬虫中使用无头浏览器 PhantomJS

一、简介

一个基于webkit内核的无头浏览器。本章主要是使用PhantomJS对网页中的JS进行处理。

1. 内置对象:

var system=require('system');    //获得系统操作对象,包括命令行参数、phantomjs系统设置等信息
var page = require('webpage');   //获取操作dom或web网页的对象,通过它可以打开网页、接收网页内容、request、response参数,其为最核心对象。
var fs = require('fs');          //获取文件系统对象,通过它可以操作操作系统的文件操作,包括read、write、move、copy、delete等。

2. Python的爬虫方案里,对javascript通常有几种解决方案

  • 写代码模拟js逻辑
  • 调用一个有界面浏览器,如selenium
  • 使用一个无界面浏览器,如casperjs,phantomjs
  • 自己基于js引擎实现轻量级浏览器。pyv8的示例里有一个基于v8实现的简易浏览器模型。

3. 几种无界面浏览器说明

  • casperjs,phantomjs:非python,可以通过命令行调用。phantomjs还有一个非官方的webdriver协议实现,可通过selenium调phantomjs实现无界面。
  • ghost,spynner等,py定制的webkit。

二、安装

1. windows环境安装

下载地址:
http://phantomjs.org/

下载后解压缩,放到Python目录里。

2. ubuntu环境安装方法1

注意不要使用 sudo apt-get install phantomjs
下载地址:http://phantomjs.org/download.html

sudo apt-get install nodejs-legacy
sudo apt-get install npm
sudo apt purge phantomjs
npm install -g --registry https://registry.npm.taobao.org phantomjs

3. ubuntu环境安装方法2

tar -xvf phantomjs-2.1.1-linux-x86_64.tar.bz2
–将程序移到一个合适的位置

sudo mv phantomjs-2.1.1-linux-x86_64 /usr/local/src/phantomjs
—-创建软链接到环境变量中。这样可以直接在shell中使用phantomjs命令

sudo ln -sf /usr/local/src/phantomjs/bin/phantomjs /usr/local/bin/phantomjs
—-检查是否正常工作
phantomjs

4. CentOS环境安装

下载http://blog.csdn.net/qq_34023608/article/details/52217281

wget https://bitbucket.org/ariya/phantomjs/downloads/phantomjs-2.1.1-linux-x86_64.tar.bz2
tar -xjvf phantomjs-2.1.1-linux-x86_64.tar.bz2
chmod +x /PATH/phantomjs-2.1.1/bin/phantomjs
sudo ln -s ~/PATH/phantomjs-2.1.1/bin/phantomjs /usr/local/bin/phantomjs
yum install fontconfig freetype2
phantomjs -v

三、示例,启动js脚本

把代码保存成.js文件,然后使用下面命令运行:

phantomjs.exe 1.js

1. 获取脚本参数

var system = require('system');
if (system.args.length === 1) {
    console.log('Try to pass some args when invoking this script!');
} else {
    system.args.forEach(function (arg, i) {
            console.log(i + ': ' + arg);
    });
}
phantom.exit();

输出结果:
这里写图片描述

2. 截屏

var page = require('webpage').create();
page.open('http://www.baidu.com', function () {
    page.render('example.png');
    phantom.exit();
});

3. 运行js 计算页面运行时间

var page = require('webpage').create(),
    system = require('system'),
    t, address;

phantom.outputEncoding="gbk";  //按实际编码格式填写
if (system.args.length === 1) {
    console.log('Usage: loadspeed.js <some URL>');
    phantom.exit(1);
} else {
    t = Date.now();
    address = system.args[1];
    page.open(address, function (status) {
        if (status !== 'success') {
            console.log('FAIL to load the address');
        } else {
            t = Date.now() - t;
            console.log('Page title is ' + page.evaluate(function () {
                return document.title;
            }));
            console.log('Loading time ' + t + ' msec');
        }
        phantom.exit();
    });
}

运行:
这里写图片描述

4. 取标题

var page = require('webpage').create();
page.open('http://www.csdn.net', function(status) {
  var title = page.evaluate(function() {
    return document.title;
  });
  phantom.outputEncoding = "gbk";
  console.log('Page title is ' + title);
  phantom.exit();
});

5. 取元素,修改UserAgent

var page = require('webpage').create();
console.log('The default user agent is ' + page.settings.userAgent);
page.settings.userAgent = 'SpecialAgent';
page.open('http://www.httpuseragent.org', function (status) {
    if (status !== 'success') {
        console.log('Unable to access network');
    } else {
        var ua = page.evaluate(function () {
            return document.getElementById('myagent').innerText;
        });
        console.log(ua);
    }
    phantom.exit();
});

6. 注入js

var page = require('webpage').create();
page.open('http://www.sample.com', function() {
  page.includeJs("http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js", function() {
    page.evaluate(function() {
      $("button").click();
    });
    phantom.exit()
  });
});

四、 Python+Selenium+PhantomJS

下面Python与PhantomJS结合使用。

1. 输出title

#!/usr/bin/python

from selenium import webdriver
driver = webdriver.PhantomJS(executable_path="phantomjs.exe")
driver.get("http://www.baidu.com")
data = driver.title
print (data)

2. 输出内容到文件

#!/usr/bin/python

from selenium import webdriver
driver = webdriver.PhantomJS(executable_path="phantomjs.exe")

driver.get("http://item.jd.com/2914823.html")

print (driver.page_source)
fo = open("aaaa1.txt", "wb")
fo.write(driver.page_source.encode())
fo.close()
driver.quit()

3. 截屏

#!/usr/bin/python
#coding=utf-8
from selenium import webdriver  
driver=webdriver.PhantomJS(executable_path="phantomjs.exe")  
driver.get("http://www.csdn.net")  
data = driver.title
driver.save_screenshot('csdn.png')
print(data)

4. 选择器

#!/usr/bin/python
#coding=utf-8
from selenium import webdriver
driver = webdriver.PhantomJS(executable_path='phantomjs.exe')
#executable_path为你的phantomjs可执行文件路径
driver.get("http://news.sohu.com/scroll/")

#或得js变量的值
r = driver.execute_script("return newsJason")
print (r)

#selenium在webdriver的DOM中使用选择器来查找元素,包含id,class_name,css_selector,link_text,name,tag_name,tag_name,xpath等等
print (driver.find_element_by_tag_name("div").text)
print (driver.find_element_by_css_selector("#content").text)
print (driver.find_element_by_id("content").text)

5. 截全屏

#!/usr/bin/python
#coding=utf-8
import time
from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities


def cpature(url):
    dcap = dict(DesiredCapabilities.PHANTOMJS)
    dcap["phantomjs.page.settings.userAgent"] = (
        "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36"
    )

    driver = webdriver.PhantomJS(desired_capabilities=dcap)
    driver.get(url)
    js="document.body.scrollTop+=100"
    height = driver.execute_script("return document.body.scrollHeight");
    count = int(height / 100) 
    print('the height is %d,滚动 %d 次' % (height, count))
    print('result url is: %s' % driver.current_url)
    for i in range(0, count):
        print('scroll index: %d' % i)
        driver.implicitly_wait(30)
        time.sleep(1)
        driver.execute_script(js)

    html=driver.page_source
    driver.save_screenshot('1.png')
    driver.quit()
    return html

url="http://www.sohu.com.cn/"
text=cpature(url)

发现的问题:网页会遗失一些图片不显示,可能图片是异步加载的;在CentOS下运行时,缺失更严重。

参考:
http://blog.csdn.net/eastmount/article/details/47023199

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

编程圈子

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值