Selenium + PhantomJS + python 简单实现爬虫的功能

1438 篇文章 112 订阅
1390 篇文章 66 订阅

Selenium

一、简介

selenium是一个用于Web应用自动化程序测试的工具,测试直接运行在浏览器中,就像真正的用户在操作一样

selenium2支持通过驱动真实浏览器(FirfoxDriver,IternetExplorerDriver,OperaDriver,ChromeDriver)

selenium2支持通过驱动无界面浏览器(HtmlUnit,PhantomJs)

二、安装

Windows

第一种方法是:下载源码安装,下载地址(https://pypi.python.org/pypi/selenium)解压并把整个目录放到C:\Python27\Lib\site-packages下面

第二种方法是:可以直接在C:\Python27\Scripts 下输入命令安装 pip install -U selenium

Linux

1 sudo pip install selenium

PhantomJS

一、简介

PhantomJS 是一个基于 WebKit(WebKit是一个开源的浏览器引擎,Chrome,Safari就是用的这个浏览器引擎) 的服务器端 JavaScript API,

主要应用场景是:无需浏览器的 Web 测试,页面访问自动化,屏幕捕获,网络监控

二、安装

Windows
下载源码安装,下载地址(http://phantomjs.org/download.html)解压并把解压缩的路径添加到环境变量中即可,我自己的放到了C:\Python27\Scripts 下面

Linux 1 sudo apt-get install PhantomJS

Selenium + PhantomJS + python 简单实现爬虫的功能

python可以使用selenium执行javascript,selenium可以让浏览器自动加载页面,获取需要的数据。selenium自己不带浏览器,可以使用第三方浏览器如Firefox,Chrome等,也可以使用headless浏览器如PhantomJS在后台执行。

在工作用遇到一个问题,当加载一个手机端的URL时候,会加载不上,需要我们在请求头中设置一个User-Agent,设置完以后就可以打开了(Windows下执行,linux下执行的话就不用加executable_path=‘C:\Python27\Scripts\phantomjs.exe’)

from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
 
dcap = dict(DesiredCapabilities.PHANTOMJS)  #设置userAgent
dcap["phantomjs.page.settings.userAgent"] = ("Mozilla/5.0 (Macintosh; Intel Mac OS X 10.9; rv:25.0) Gecko/20100101 Firefox/25.0 ")
 
obj = webdriver.PhantomJS(executable_path='C:\Python27\Scripts\phantomjs.exe',desired_capabilities=dcap) #加载网址
obj.get('http://wap.95533pc.com')#打开网址
obj.save_screenshot("1.png")   #截图保存
obj.quit()  # 关闭浏览器。当出现异常时记得在任务浏览器中关闭PhantomJS,因为会有多个PhantomJS在运行状态,影响电脑性能

一、超时设置

webdriver类中有三个和时间相关的方法:

1.pageLoadTimeout 设置页面完全加载的超时时间,完全加载即完全渲染完成,同步和异步脚本都执行完

2.setScriptTimeout 设置异步脚本的超时时间

3.implicitlyWait 识别对象的智能等待时间

下面我们以获取校花网title为例来验证效果,因为校花网中图片比较多,所以加载的时间比较长,更能时间我们的效果(另一原因我就不说了,这样才能让我们学起来带劲,哈哈!!!)

from selenium import webdriver
obj = webdriver.PhantomJS(executable_path="D:\Python27\Scripts\phantomjs.exe")
obj.set_page_load_timeout(5)
try:
    obj.get('http://www.xiaohuar.com')
    print obj.title
except Exception as e:
    print e

二、元素的定位

对象的定位是通过属性定位来实现的,这种属性就像人的身份证信息一样,或是其他的一些信息来找到这个对象,那我们下面就介绍下Webdriver提供的几个常用的定位方法
1

<input id="kw" name="wd" class="s_ipt" value="" maxlength="255" autocomplete="off">

上面这个是百度的输入框,我们可以发现我们可以用id来定位这个标签,然后就可以进行后面的操作了

更多具体关于XPath的信息,请具体参照 http://www.cnblogs.com/hyddd/archive/2009/05/22/1487332.html

from selenium import webdriver
obj = webdriver.PhantomJS(executable_path="D:\Python27\Scripts\phantomjs.exe")
obj.set_page_load_timeout(5)
try:
    obj.get('http://www.baidu.com')
    obj.find_element_by_id('kw')                    #通过ID定位
    obj.find_element_by_class_name('s_ipt')         #通过class属性定位
    obj.find_element_by_name('wd')                  #通过标签name属性定位
    obj.find_element_by_tag_name('input')           #通过标签属性定位
    obj.find_element_by_css_selector('#kw')         #通过css方式定位
    obj.find_element_by_xpath("//input[@id='kw']")  #通过xpath方式定位
    obj.find_element_by_link_text("贴吧")           #通过xpath方式定位
 
    print obj.find_element_by_id('kw').tag_name   #获取标签的类型
except Exception as e:
    print e  

三、浏览器的操作

1、调用启动的浏览器不是全屏的,有时候会影响我们的某些操作,所以我们可以设置全屏

from selenium import webdriver
obj = webdriver.PhantomJS(executable_path="D:\Python27\Scripts\phantomjs.exe")
obj.set_page_load_timeout(5)
obj.maximize_window()  #设置全屏
try:
    obj.get('http://www.baidu.com')
    obj.save_screenshot('11.png')  # 截取全屏,并保存
except Exception as e:
    print e

2、设置浏览器宽、高

from selenium import webdriver
obj = webdriver.PhantomJS(executable_path="D:\Python27\Scripts\phantomjs.exe")
obj.set_page_load_timeout(5)
obj.set_window_size('480','800') #设置浏览器宽480,高800
try:
    obj.get('http://www.baidu.com')
    obj.save_screenshot('12.png')  # 截取全屏,并保存
except Exception as e:
    print e

3、操作浏览器前进、后退

from selenium import webdriver
obj = webdriver.PhantomJS(executable_path="D:\Python27\Scripts\phantomjs.exe")
try:
    obj.get('http://www.baidu.com')   #访问百度首页
    obj.save_screenshot('1.png')
    obj.get('http://www.sina.com.cn') #访问新浪首页
    obj.save_screenshot('2.png')
    obj.back()                           #回退到百度首页
    obj.save_screenshot('3.png')
    obj.forward()                        #前进到新浪首页
    obj.save_screenshot('4.png')
except Exception as e:
    print e

四、操作测试对象

定位到元素以后,我们就应该对相应的对象进行某些操作,以达到我们某些特定的目的,那我们下面就介绍下Webdriver提供的几个常用的操作方法

from selenium import webdriver
obj = webdriver.PhantomJS(executable_path="D:\Python27\Scripts\phantomjs.exe")
obj.set_page_load_timeout(5)
try:
    obj.get('http://www.baidu.com')
    print obj.find_element_by_id("cp").text  # 获取元素的文本信息
    obj.find_element_by_id('kw').clear()              #用于清除输入框的内容
    obj.find_element_by_id('kw').send_keys('Hello')  #在输入框内输入Hello
    obj.find_element_by_id('su').click()              #用于点击按钮
    obj.find_element_by_id('su').submit()             #用于提交表单内容
 
except Exception as e:
    print e

五、键盘事件

1、键盘按键用法

from selenium.webdriver.common.keys import Keys
obj = webdriver.PhantomJS(executable_path="D:\Python27\Scripts\phantomjs.exe")
obj.set_page_load_timeout(5)
try:
    obj.get('http://www.baidu.com')
    obj.find_element_by_id('kw').send_keys(Keys.TAB)   #用于清除输入框的内容,相当于clear()
    obj.find_element_by_id('kw').send_keys('Hello')   #在输入框内输入Hello
    obj.find_element_by_id('su').send_keys(Keys.ENTER) #通过定位按钮,通过enter(回车)代替click()
 
except Exception as e:
    print e

2、键盘组合键使用

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
obj = webdriver.PhantomJS(executable_path="D:\Python27\Scripts\phantomjs.exe")
obj.set_page_load_timeout(5)
try:
    obj.get('http://www.baidu.com')
    obj.find_element_by_id('kw').send_keys(Keys.TAB)   #用于清除输入框的内容,相当于clear()
    obj.find_element_by_id('kw').send_keys('Hello')   #在输入框内输入Hello
    obj.find_element_by_id('kw').send_keys(Keys.CONTROL,'a')   #ctrl + a 全选输入框内容
    obj.find_element_by_id('kw').send_keys(Keys.CONTROL,'x')   #ctrl + x 剪切输入框内容
 
except Exception as e:
    print e

六、中文乱码问题

selenium2 在python的send_keys()中输入中文会报错,其实在中文前面加一个u变成unicode就能搞定了

七、鼠标事件

1、鼠标右击

from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
obj = webdriver.PhantomJS(executable_path="D:\Python27\Scripts\phantomjs.exe")
try:
    obj.get("http://pan.baidu.com")
    obj.find_element_by_id('TANGRAM__PSP_4__userName').send_keys('13201392325')   #定位并输入用户名
    obj.find_element_by_id('TANGRAM__PSP_4__password').send_keys('18399565576lu') #定位并输入密码
    obj.find_element_by_id('TANGRAM__PSP_4__submit').submit()                       #提交表单内容
    f = obj.find_element_by_xpath('/html/body/div/div[2]/div[2]/....')             #定位到要点击的标签
    ActionChains(obj).context_click(f).perform()                                        #对定位到的元素进行右键点击操作
 
except Exception as e:
    print e

2、鼠标双击

from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
obj = webdriver.PhantomJS(executable_path="D:\Python27\Scripts\phantomjs.exe")
try:
    obj.get("http://pan.baidu.com")
    obj.find_element_by_id('TANGRAM__PSP_4__userName').send_keys('13201392325')   #定位并输入用户名
    obj.find_element_by_id('TANGRAM__PSP_4__password').send_keys('18399565576lu') #定位并输入密码
    obj.find_element_by_id('TANGRAM__PSP_4__submit').submit()                       #提交表单内容
    f = obj.find_element_by_xpath('/html/body/div/div[2]/div[2]/....')             #定位到要点击的标签
    ActionChains(obj).double_click(f).perform()                                        #对定位到的元素进行双击操作
 
except Exception as e:
    print e

技能提升

最后感谢每一个认真阅读我文章的人,看着粉丝一路的上涨和关注,礼尚往来总是要有的,虽然不是什么很值钱的东西,如果你用得到的话可以直接拿走
在这里插入图片描述
这些资料,对于做【软件测试】的朋友来说应该是最全面最完整的备战仓库,这个仓库也陪伴我走过了最艰难的路程,希望也能帮助到你!凡事要趁早,特别是技术行业,一定要提升技术功底。希望对大家有所帮助…….
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
需要的添加的jar包及工具:我这里使用maven来构建项目,添加依赖如下:   org.seleniumhq.selenium   selenium-java   3.2.0    PhantomJs工具到官网去下载:http://phantomjs.org/download.html 尽量都使用最新版本,不然会出现版本兼容的情况。 这里有一个已经写好的获取PhantomJSDriver的工具类 public static WebDriver getPhantomJs() {   String osname = System.getProperties().getProperty("os.name");   if (osname.equals("Linux")) {//判断系统的环境win or Linux     System.setProperty("phantomjs.binary.path", "/usr/bin/phantomjs");   } else {     System.setProperty("phantomjs.binary.path", "./phantomjs/win/phantomjs.exe");//设置PhantomJs访问路径   }   DesiredCapabilities desiredCapabilities = DesiredCapabilities.phantomjs();   //设置参数   desiredCapabilities.setCapability("phantomjs.page.settings.userAgent", "Mozilla/5.0 (Windows NT 6.3; Win64; x64; rv:50.0) Gecko/20100101 Firefox/50.0");   desiredCapabilities.setCapability("phantomjs.page.customHeaders.User-Agent", "Mozilla/5.0 (Windows NT 6.3; Win64; x64; rv:50.0) Gecko/20100101   Firefox/50.0");   if (Constant.isProxy) {//是否使用代理     org.openqa.selenium.Proxy proxy = new org.openqa.selenium.Proxy();     proxy.setProxyType(org.openqa.selenium.Proxy.ProxyType.MANUAL);     proxy.setAutodetect(false);     String proxyStr = "";     do {       proxyStr = ProxyUtil.getProxy();//自定义函数,返回代理ip及端口     } while (proxyStr.length() == 0);     proxy.setHttpProxy(proxyStr);     desiredCapabilities.setCapability(CapabilityType.PROXY, proxy);   }   return new PhantomJSDriver(desiredCapabilities); } 获取方式     try{     WebDriver webDriver = PhantomJsUtil.getPhantomJs();     webDriver.get(url);     SleepUtil.sleep(Constant.SEC_5);     PhantomJsUtil.screenshot(webDriver);     WebDriverWait wait = new WebDriverWait(webDriver, 10);     wait.until(ExpectedConditions.presenceOfElementLocated(By.id(inputId)));//开始打开网页,等待输入元素出现     Document document = Jsoup.parse(webDriver.getPageSource());     //TODO  剩下页面的获取就按照Jsoup获取方式来做   }finally{     if (webDriver != null) {       webDriver.quit();     }   } python版使用webdriver+PhantomJs爬虫使用,参考http://www.cnblogs.com/kuqs/p/6395284.html

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值