您的位置:首页 > 编程语言 > Python开发

python+selenium+phantomjs实现爬虫功能

2017-11-22 10:37 661 查看

一.phantomjs介绍

phantomjs是一个基于webkit内核的无头浏览器,即没有UI界面,即它就是一个浏览器,只是其内的点击、翻页等人为相关操作需要程序设计实现

提供javascript API接口,即通过编写js程序可以直接与webkit内核交互,在此之上可以结合java语言等,通过java调用js等相关操作,从而解决了以前c/c++才能比较好的基于webkit开发优质采集器的限制。

提供windows、linux、mac等不同os的安装使用包,也就是说可以在不同平台上二次开发采集项目或是自动项目测试等工作。

官方网站:http://phantomjs.org/

快速入门:http://phantomjs.org/quick-start.html

二.安装phantomjs

phantomjs1.9.1以上版本

从官网下载phantomjs-2.1.1-linux-x86_64.tar.bz2,直接解压即可。

进入bin目录,有个phantomjs可执行文件,直接执行js文件。

如:test.js文件:

console.log('Hello world!');
phantom.exit();//这一行表示退出命令行


为了方便使用phantomjs命令,建立软连接,把phantomjs文件软链到/usr/bin目录下。

ln -s /home/zhb/software/phantomjs-2.1.1-linux-x86_64/bin/phantomjs /usr/bin/

三.python及Selenium模块安装

python安装过程省略。

Selenium是一个用于Web应用程序测试的工具。Selenium测试直接运行在浏览器中,就像真正的用户在操作一样。支持的浏览器包括IE(7, 8, 9, 10, 11),Mozilla Firefox,Safari,Google Chrome,Opera等。这个工具的主要功能包括:测试与浏览器的兼容性——测试你的应用程序看是否能够很好得工作在不同浏览器和操作系统之上。测试系统功能——创建回归测试检验软件功能和用户需求。支持自动录制动作和自动生成 .Net、Java、Perl等不同语言的测试脚本。

官方网站:http://www.seleniumhq.org/

安装selenium模块。

下载selenium:

https://pypi.python.org/pypi/selenium

安装:

python setup.py install

测试是否安装成功:

from selenium import webdriver

四.简单示例

from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
from selenium.webdriver.common.action_chains import ActionChains

#设置浏览器的请求头及一些参数
dcap = dict(DesiredCapabilities.PHANTOMJS)
dcap["phantomjs.page.settings.userAgent"] = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.221 Safari/537.36 SE 2.X MetaSr 1.0"
#不加载图片
dcap["phantomjs.page.settings.loadImages"] = False

driver = webdriver.PhantomJS(executable_path="/usr/bin/phantomjs", desired_capabilities = dcap)
#设置页面最长加载时间为40s
driver.set_page_load_timeout(40)

driver.get("https://www.baidu.com/")

#打印title
print driver.title

#打印当前url
print driver.current_url

#调用find_element_by_css_selector函数按照css样式取出css元素
#如果该样式不存在,会抛出异常
#find_elements_by_css_selector是取出所有符合条件的css样式表,返回的数组
a = driver.find_element_by_css_selector('div#ui a[name="tj_trnews"]')
a_text = a.text
a_href = a.get_attribute('href')

b = driver.find_elements_by_css_selector('div#ui a[name="tj_trnews"]')
b_0_text = b[0].text
b_0_href = b[0].get_attribute('href')

#点击某个a标签
driver.find_element_by_css_selector('a[data-reactid=".2.1.2.0.0.0.0:$tab_1.0"]').click()

#判断ajax请求后,css元素是否加载成功
#10s内每隔500ms刷新一次页面变化,判断该元素是否成功加载
#lambda表达式返回bool值,也可以用其他表达式
def is_css_selector_loaded(css_selector, wait_time=10):
try:
wait_for_ajax_element=WebDriverWait(driver, wait_time)
wait_for_ajax_element.until(
lambda the_driver:the_driver.find_element_by_css_selector(css_selector).is_displayed())
return True
except Exception, e:
print 'fail to load css selector by ajax:%s' % (css_selector)
return False

#执行js代码
div_block_js = "sub_titles=document.querySelectorAll('div.yx-cp-tabNav-dropdown');for(i=0;i<sub_titles.length;i++){sub_titles[i].style.display='block';}"
driver.execute_script(div_block_js)#利用js把隐藏的div显示出来

#鼠标移到某个元素悬停
ActionChains(driver).move_to_element(a).context_click().perform()

#关闭所有窗口
driver.quit()


参考文档:

http://www.seleniumhq.org/docs/03_webdriver.jsp

五. 利用python的requests模块发送http请求

以上方法是利用phantomjs模拟浏览器来抓取并解析页面元素,也可以用python的requests模块发送http请求获得数据(实际就是刷接口,解析json数据),如果接口返回的不是json串,那还是用phantomjs浏览器抓取元素比较方便,或者用Beautiful Soup来解析html代码。

首先确保python安装了urllib和requests模块。

下面是示例代码:

import urllib
import requests
import json

#发送post请求
post_headers = {"Referer":"https://youpin.mi.com", "Content-Type":"application/x-www-form-urlencoded"}
post_params = urllib.urlencode({"data":'''{"uClassList":{"model":"Homepage","action":"GetUclassList","parameters":{"id":131056}}}'''})
http_result = requests.post("https://youpin.mi.com/app/shopv3/pipe", headers = post_headers, data = post_params)

#解析返回的json
http_result = json.loads(http_result.text)
if http_result.has_key('code'):
print http_result["code"]["pid"]

#发送get请求
http_headers = {"Content-Type":"application/json;charset=UTF-8"}
http_result = requests.get("http://blog.csdn.net/okiwilldoit/article/GetMyYunStatus", headers = http_headers)

#解析HTTP response
result_json = json.loads(http_result.text)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: