背景知识:

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

selenium是一个测试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

参考文献:

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

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

http://www.ruanyifeng.com/blog/2009/07/xpath_path_expressions.html

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


phantomJS设置头部的userAgent
from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities dcap = dict(DesiredCapabilities.PHANTOMJS)
dcap["phantomjs.page.settings.userAgent"] = (
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10.9; rv:25.0) Gecko/20100101 Firefox/25.0 "
) driver = webdriver.PhantomJS(executable_path='./phantomjs', desired_capabilities=dcap)
driver.get("http://dianping.com/")
cap_dict = driver.desired_capabilities
for key in cap_dict:
print '%s: %s' % (key, cap_dict[key])
print driver.current_url
driver.quit
查看是否成功

agent = browser.execute_script("return navigator.userAgent")
print agent

selenium+phantomJS学习使用记录的更多相关文章

  1. C#使用Selenium+PhantomJS抓取数据

    本文主要介绍了C#使用Selenium+PhantomJS抓取数据的方法步骤,具有很好的参考价值,下面跟着小编一起来看下吧 手头项目需要抓取一个用js渲染出来的网站中的数据.使用常用的httpclie ...

  2. selenium + phantomjs 爬取落网音乐

    题记: 作为一个业余程序猿,最大的爱好就是电影和音乐了,听音乐当然要来点有档次的.落网的音乐的逼格有点高,一听听了10年.学习python一久了,于是想用python技术把落网的音乐爬下来随便听. 目 ...

  3. 使用selenium+phantomJS实现网页爬取

    有些网站反爬虫技术设计的非常好,很难采用WebClient等技术进行网页信息爬取,这时可以考虑采用selenium+phantomJS模拟浏览器(其实是真实的浏览器)的方式进行信息爬取.之前一直使用的 ...

  4. 数据抓取的艺术(一):Selenium+Phantomjs数据抓取环境配置

     数据抓取的艺术(一):Selenium+Phantomjs数据抓取环境配置 2013-05-15 15:08:14 分类: Python/Ruby     数据抓取是一门艺术,和其他软件不同,世界上 ...

  5. 基于selenium+phantomJS的动态网站全站爬取

    由于需要在公司的内网进行神经网络建模试验(https://www.cnblogs.com/NosenLiu/articles/9463886.html),为了更方便的在内网环境下快速的查阅资料,构建深 ...

  6. [Python爬虫] 之一 : Selenium+Phantomjs动态获取网站数据信息

    本人刚才开始学习爬虫,从网上查询资料,写了一个利用Selenium+Phantomjs动态获取网站数据信息的例子,当然首先要安装Selenium+Phantomjs,具体的看 http://www.c ...

  7. [Python爬虫] 之九:Selenium +phantomjs抓取活动行中会议活动(单线程抓取)

    思路是这样的,给一系列关键字:互联网电视:智能电视:数字:影音:家庭娱乐:节目:视听:版权:数据等.在活动行网站搜索页(http://www.huodongxing.com/search?city=% ...

  8. (java)selenium webdriver学习---实现简单的翻页,将页面内容的标题和标题链接取出

    selenium webdriver学习---实现简单的翻页,将页面内容的标题和标题链接取出: 该情况适合能能循环page=1~n,并且每个网页随着循环可以打开的情况, 注意一定是自己拼接的url可以 ...

  9. (java)selenium webdriver学习---三种等待时间方法:显式等待,隐式等待,强制等待

    selenium webdriver学习---三种等待时间方法:显式等待,隐式等待,强制等待 本例包括窗口最大化,刷新,切换到指定窗口,后退,前进,获取当前窗口url等操作: import java. ...

随机推荐

  1. JS操作cookie以及本地存储(sessionStorage 和 localStorage )

    JS操作cookie cookie的操作用两种方式 1.substring //创建cookie function setCookie(name,value,expires,path,domain,s ...

  2. 如何查看Servlet、JSP的版本(Tomcat V7.0.70)

    1. 简要说明:Tomcat6.0 所支持的是Servlet2.5,Tomcat 7.0 所支持的Servlet3.0,Servlet2.5 和Servlet3.0的差异较大,对于Servlet3.0 ...

  3. Android Mina框架的学习笔记

    Apache MINA(Multipurpose Infrastructure for Network Applications) 是 Apache 组织一个较新的项目,它为开发高性能和高可用性的网络 ...

  4. Ionic 小节

    教程 http://www.runoob.com/ionic/ionic-install.html 最后报错,发现是jdk版本过低,升级到8.0后正常 分析:nodejs.cordova.ionic. ...

  5. UIAlertView

    1.Title 获取或设置UIAlertView上的标题. 2.Message 获取或设置UIAlertView上的消息 UIAlertView *alertView = [[UIAlertViewa ...

  6. autolayout也会锁死

    This application is modifying the autolayout engine from a background thread, which can lead to engi ...

  7. ftp主动模式 被动模式 和iptables 设置

    FTP协议有两种工作方式:PORT方式和PASV方式,中文意思为主动式和被动式. Port模式:ftp server:tcp 21 <------client:dynamic    ftp se ...

  8. networkcommon v3开源消息框架资料

    http://www.cnblogs.com/csdev/category/870400.html

  9. Inventory Pro 装备拾取的实现

    以后都按照插件使用,提出问题,回答问题的方式来进行总结和学习 效果图 1.运行相关的例子,场景中出现4个矩形,这4个矩形是用来模拟物品掉落的包裹,移动Player靠近物品 2.使用鼠标点击物品正方体, ...

  10. BCB 多线程的同步与协调

    多线程编程是提高系统资源利用率的一种常见方式.它占用的资源更小,启动更快,还可以实现在后台运行一些需时较长的操作.[喝小酒的网摘]http://blog.hehehehehe.cn/a/8498.ht ...