zoukankan      html  css  js  c++  java
  • Selenium + PhantomJS + python 简单实现动态页面的爬取

    Selenium

    一、简介

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

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

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

    selenium2和selenium区别在于2中把WebDrive整合在了一起

    Selenium 的工作原理:

    Selenium RC(selenium核心)

      Selenium RC 使用的是javascript注入的方式跟浏览器打交道。这样 Selenium RC 需要启动一个Server,然后将操作页面元素的API 转成javascript脚本,再把这段脚本注入到浏览器中去执行。而通过这种javascript注入的方式一来太依赖翻译成javascript质量的好坏,二来javascript存在同源问题。这使测试变得不那么容易。

    WebDriver(selenium2核心)

      与Selenium RC 不同的是Selenium WebDriver 针对不同的浏览器进行独立开发Driver,利用浏览器的原生API去直接操作浏览器和页面元素,这样大大提高了测试的稳定性和速度。当然因为不同的浏览器对Web元素操作和呈现多多少少会存在一些差异,这也就造成现在不同的浏览器需要有对应不同的Driver(ChromeDriver ,IEDriver等等)。

    二、安装 

    Windows

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

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

    Linux

    sudo pip install selenium

    Selenium + PhantomJS + python 简单实现动态网页爬取

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

    linux下执行的话就不用加executable_path='C:Python27Scriptsphantomjs.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:Python27Scriptsphantomjs.exe',desired_capabilities=dcap) #加载网址
    obj.get('http://wap.95533pc.com')#打开网址
    html = obj.page_source 获取源码
    obj.save_screenshot(
    "1.png") #截图保存 obj.quit() # 关闭浏览器。当出现异常时记得在任务浏览器中关闭PhantomJS,因为会有多个PhantomJS在运行状态,影响电脑性能

    一、超时设置

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

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

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

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

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

    二、元素的定位

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

    <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:Python27Scriptsphantomjs.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:Python27Scriptsphantomjs.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:Python27Scriptsphantomjs.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:Python27Scriptsphantomjs.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:Python27Scriptsphantomjs.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:Python27Scriptsphantomjs.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:Python27Scriptsphantomjs.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:Python27Scriptsphantomjs.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:Python27Scriptsphantomjs.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

     八、cookie处理

    1、获取cookie

    from selenium import webdriver
    from selenium.webdriver.common.action_chains import ActionChains
    obj = webdriver.PhantomJS(executable_path="D:Python27Scriptsphantomjs.exe")
    try:
        obj.get("http://pan.baidu.com")
       obj.get_cookies()        # 获取cookie
    obj.get_cookie(name) # 获取指定的cookie
    except Exception as e: print e

    2、添加cookie

    from selenium import webdriver
    from selenium.webdriver.common.action_chains import ActionChains
    obj = webdriver.PhantomJS(executable_path="D:Python27Scriptsphantomjs.exe")
    try:
        obj.get("http://pan.baidu.com")
        c1 = {u"name":u"ryan"}
       obj.add_cookie(c1) # 添加cookie
    time.sleep(3)
    obj.refresh() #刷新页面
    except Exception
    as e: print e

     


    参考:

    http://www.cnblogs.com/yoyoketang/p/6536253.html

    http://www.cnblogs.com/luxiaojun/p/6144748.html

    http://blog.csdn.net/qq_25794017/article/details/78418091

  • 相关阅读:
    微信小程序获取用户绑定手机号码完整版
    SQL读取当天的数据
    Android 百度离线地图(由apk文件转入手机内部存储)
    解决windows家庭版系统不支持远程桌面功能问题
    微信小程序携参跳转页面
    微信小程序 websocket 封装
    微信小程序HTTP请求封装
    Ionic项目打包Android在9版本以上不能进行HTTP通信问题
    Ionic 使用 MQTT
    Ionic HTTP 请求
  • 原文地址:https://www.cnblogs.com/domestique/p/7896870.html
Copyright © 2011-2022 走看看