这是我学习爬虫比较深入的一步了,大部分的网页抓取用urllib2都可以搞定,但是涉及到JavaScript的时候,urlopen就完全傻逼了,所以不得不用模拟浏览器,方法也有很多,此处我采用的是selenium2+phantomjs,原因在于:

selenium2支持所有主流的浏览器和phantomjs这些无界面的浏览器,我开始打算用Chrome,但是发现需要安装一个什么Chrome驱动,于是就弃用了,选择phantomjs,而且这个名字听起来也比较洋气。

上网查了很多资料,发现网上selenium2+phantomjs的使用方法的中文资源十分欠缺,不得不阅读晦涩的官方文档,所以这里记下目前已经实现的操作,再加上一些我个人遇到的问题以及对应的解决方案。

背景知识:

phantomjs是一个基于webkit的没有界面的浏览器,所以运行起来比完整的浏览器要高效。

selenium的英文原意是Se,化学元素,这里是一个测试web应用的工具,目前是2.42.1版本,和1版的区别在于2.0+中把WebDrive整合在了一起。

selenium2支持的Python版本:2.7, 3.2, 3.3 and 3.4

如果需要进行远程操作的话,就需要额外安装selenium server

安装:

先装selenium2,哪种方式装都可以,我一般都是直接下载压缩包,然后用python setup.py install命令来装,selenium 2.42.1的下载地址:https://pypi.python.org/pypi/selenium/2.42.1

然后下载phantomjs,https://bitbucket.org/ariya/phantomjs/downloads/phantomjs-1.9.7-windows.zip,解压后可以看到一个phantomjs.exe的文件

范例1:

#coding=utf-8
from selenium import webdriver driver = webdriver.PhantomJS(executable_path='C:\Users\Gentlyguitar\Desktop\phantomjs-1.9.7-windows\phantomjs.exe')
driver.get("http://duckduckgo.com/")
driver.find_element_by_id('search_form_input_homepage').send_keys("Nirvana")
driver.find_element_by_id("search_button_homepage").click()
print driver.current_url
driver.quit()

其中的executable_path就是刚才phantomjs.exe的路径,运行结果:

https://duckduckgo.com/?q=Nirvana

Walk through of the example:

值得一提的是:

get方法会一直等到页面被完全加载,然后才会继续程序

但是对于ajax: It’s worth noting that if your page uses a lot of AJAX on load then WebDriver may not know when it has completely loaded

send_keys就是填充input

范例2:

#coding=utf-8
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver import ActionChains
import time
import sys driver = webdriver.PhantomJS(executable_path='C:\Users\Gentlyguitar\Desktop\phantomjs-1.9.7-windows\phantomjs.exe')
driver.get("http://www.zhihu.com/#signin")
#driver.find_element_by_name('email').send_keys('your email')
driver.find_element_by_xpath('//input[@name="password"]').send_keys('your password')
#driver.find_element_by_xpath('//input[@name="password"]').send_keys(Keys.RETURN)
time.sleep(2)
driver.get_screenshot_as_file('show.png')
#driver.find_element_by_xpath('//button[@class="sign-button"]').click()
driver.find_element_by_xpath('//form[@class="zu-side-login-box"]').submit() try:
dr=WebDriverWait(driver,5)
dr.until(lambda the_driver:the_driver.find_element_by_xpath('//a[@class="zu-top-nav-userinfo "]').is_displayed())
except:
print '登录失败'
sys.exit(0)
driver.get_screenshot_as_file('show.png')
#user=driver.find_element_by_class_name('zu-top-nav-userinfo ')
#webdriver.ActionChains(driver).move_to_element(user).perform() #移动鼠标到我的用户名
loadmore=driver.find_element_by_xpath('//a[@id="zh-load-more"]')
actions = ActionChains(driver)
actions.move_to_element(loadmore)
actions.click(loadmore)
actions.perform()
time.sleep(2)
driver.get_screenshot_as_file('show.png')
print driver.current_url
print driver.page_source
driver.quit()

这个程序完成的是,登陆知乎,然后能自动点击页面下方的“更多”,以载入更多的内容

Walk through of the example:

from selenium.webdriver.common.keys import Keys,keys这个类就是键盘上的键,文中的send_keys(Keys.RETURN)就是按一个回车

from selenium.webdriver.support.ui import WebDriverWait是为了后面一个等待的操作

from selenium.webdriver import ActionChains是导入一个动作的类,这句话的写法,我找了很久

find_element推荐使用Xpath的方法,原因在于:优雅、通用、易学

Xpath表达式写法教程:http://www.ruanyifeng.com/blog/2009/07/xpath_path_expressions.html

值得注意的是,避免选择value带有空格的属性,譬如class = "country name"这种,不然会报错,大概compound class之类的错

检查用户密码是否输入正确的方法就是在填入后截屏看看

想要截屏,这么一句话就行:

driver.get_screenshot_as_file('show.png')

但是,这里的截屏是不带滚动条的,就是给你把整个页面全部照下来

try:
dr=WebDriverWait(driver,5)
dr.until(lambda the_driver:the_driver.find_element_by_xpath('//a[@class="zu-top-nav-userinfo "]').is_displayed())
except:
print '登录失败'
sys.exit(0)

是用来通过检查某个元素是否被加载来检查是否登录成功,我认为当个黑盒子用就可以了。其中5的解释:5秒内每隔500毫秒扫描1次页面变化,直到指定的元素

对于表单的提交,即可以选择登录按钮然后使用click方法,也可以选择表单然后使用submit方法,后者能应付没有登录按钮的情况,所以推荐使用submit()

对于一次点击,既可以使用click(),也可以使用一连串的action来实现,如文中:

loadmore=driver.find_element_by_xpath('//a[@id="zh-load-more"]')
actions = ActionChains(driver)
actions.move_to_element(loadmore)
actions.click(loadmore)
actions.perform()

这5句话其实就相当于一句话,find element然后click,但是action的适用范围更广,譬如在这个例子中,要点击的是一个a标签对象,我不知道为什么直接用click不行,不起作用

print driver.current_url
print driver.page_source

即打印网页的两个属性:url和source

总结:除了能解决动态页面的问题以外,用selenium用来模拟登陆也比urllib2简单得多。

参考文献:

http://www.realpython.com/blog/python/headless-selenium-testing-with-python-and-phantomjs/#.U5FXUvmSziE

http://selenium-python.readthedocs.org/getting-started.html

Xpath写法

http://www.cnblogs.com/paisen/p/3310067.html

动态爬虫——selenium2搭载phantomjs入门范例的更多相关文章

  1. python网络爬虫入门范例

    python网络爬虫入门范例 Windows用户建议安装anaconda,因为有些套件难以安装. 安装使用pip install * 找出所有含有特定标签的HTML元素 找出含有特定CSS属性的元素 ...

  2. Node.js 动态网页爬取 PhantomJS 使用入门(转)

    Node.js 动态网页爬取 PhantomJS 使用入门 原创NeverSettle101 发布于2017-03-24 09:34:45 阅读数 8309  收藏 展开 版权声明:本文为 winte ...

  3. 第三百三十七节,web爬虫讲解2—PhantomJS虚拟浏览器+selenium模块操作PhantomJS

    第三百三十七节,web爬虫讲解2—PhantomJS虚拟浏览器+selenium模块操作PhantomJS PhantomJS虚拟浏览器 phantomjs 是一个基于js的webkit内核无头浏览器 ...

  4. Python爬虫教程-26-Selenium + PhantomJS

    Python爬虫教程-26-Selenium + PhantomJS 动态前端页面 : JavaScript: JavaScript一种直译式脚本语言,是一种动态类型.弱类型.基于原型的语言,内置支持 ...

  5. QQ空间动态爬虫

    作者:虚静 链接:https://zhuanlan.zhihu.com/p/24656161 来源:知乎 著作权归作者所有.商业转载请联系作者获得授权,非商业转载请注明出处. 先说明几件事: 题目的意 ...

  6. [转]Backbone.js简单入门范例

    本文转自:http://dmyz.org/archives/598 11年刚开始用前端MVC框架时写过一篇文章,当时Knockout和Backbone都在用,但之后的项目全是在用Backbone,主要 ...

  7. scrapy + selenium 的动态爬虫

    动态爬虫 在通过scrapy框架进行某些网站数据爬取的时候,往往会碰到页面动态数据加载的情况发生,如果直接使用scrapy对其url发请求,是绝对获取不到那部分动态加载出来的数据值.但是通过观察我们会 ...

  8. crawlergo动态爬虫去除Spidername使用

    本来是想用AWVS的爬虫来联动Xray的,但是需要主机安装AWVS,再进行规则联动,只是使用其中的目标爬虫功能感觉就太重了,在github上面找到了由360 0Kee-Team团队从360天相中分离出 ...

  9. Python爬虫使用Selenium+PhantomJS抓取Ajax和动态HTML内容

    1,引言 在Python网络爬虫内容提取器一文我们详细讲解了核心部件:可插拔的内容提取器类gsExtractor.本文记录了确定gsExtractor的技术路线过程中所做的编程实验.这是第二部分,第一 ...

随机推荐

  1. Awk 从入门到放弃 (8) 动作总结之三

    awk continue 语句  awk exit 语句  awk if  语句  awk next 语句 awk break 语句

  2. bzoj1089

    题解: 递推 f[i]=f[i-1]^n+1 ans=f[d]-f[d-1] 代码: #include<bits/stdc++.h> using namespace std; int n, ...

  3. MatchText MatchStr 区别

    区别就是 是否区分大小写. str=字符串,区分 text=文本,不区分 时间长了就忘了. function AnsiCompareText(const S1, S2: string): Intege ...

  4. AFNetworking 遇到错误 Code=-1016 "Request failed: unacceptable content-type: text/plain"

    在开发过程使用了AFNetworking库,版本2.x,先运行第一个官方例子(替换GET 后面的url即可): AFHTTPRequestOperationManager *manager = [AF ...

  5. webbench源码学习-->命令行选项解析函数getopt和getopt_long函数

    对于webbench这个网站压力测试工具网上介绍的很多,有深度详解剖析的,对于背景就不在提了, 听说最多可以模拟3万个并发连接去测试网站的负载能力,这里主要是学习了一下它的源码,做点 笔记. 官方介绍 ...

  6. 切换python版本

    安装python3.6.5后, alias python='/usr/bin/python3.6'

  7. 1.1.1 A+B for Input-Output Practice (I)

    A+B for Input-Output Practice (I) Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K ...

  8. Robust Tracking via Weakly Supervised Ranking SVM

    参考文献:Yancheng Bai and Ming Tang. Robust Tracking via Weakly Supervised Ranking SVM Abstract 通常的算法:ut ...

  9. 从 0 到 1 合理高效使用 GitHub 的资料

    来自:https://github.com/xirong/my-git/blob/master/how-to-use-github.md 说明 作为一名开发者,Github上面有很多东西值得关注学习, ...

  10. git设置ss代理

    // 查看当前代理设置 git config --global http.proxy http/https协议 //设置代理(clone https://前缀的repo会走代理) git config ...