qileilove

          blog已經(jīng)轉(zhuǎn)移至github,大家請?jiān)L問 http://qaseven.github.io/

          Python Selenium的js擴(kuò)展實(shí)現(xiàn)

            python寫的數(shù)據(jù)采集,對(duì)一般有規(guī)律的頁面用 urllib2 + BeautifulSoup + 正則就可以搞定。 但是有些頁面的內(nèi)容是通過js生成,或者通過js跳轉(zhuǎn)的,甚至js中還加入幾道混淆機(jī)制;對(duì)這種涉及頁面腳本解析的內(nèi)容,前面的方式便很無力。
            這時(shí)我們需要能解析、運(yùn)行js的引擎——瀏覽器,而python selenium能提供程序與瀏覽器的交互接口,再加上phantomjs這個(gè)可以后臺(tái)運(yùn)行的瀏覽器,即使用 selenium + phantomjs 便可以解決以上的問題。
            selenium可以操作頁面的元素,并且提供執(zhí)行js腳本的接口。但其調(diào)用js腳本后并不能直接返回執(zhí)行的結(jié)果,這樣再采集內(nèi)容的過程中就會(huì)受到一些限制。 比如我們想使用頁面中的函數(shù)進(jìn)行數(shù)據(jù)轉(zhuǎn)換,或者獲取iframe里的內(nèi)容,這些js產(chǎn)生數(shù)據(jù)要傳回比較麻煩。
            所以我便寫一個(gè)簡化js數(shù)據(jù)回傳的擴(kuò)展 exescript.py
          #!/usr/bin/env python
          # -*- coding:utf-8 -*-
          #
          # created by heqingpan
          _init_js="""
          (function (){
          if (window.__e)
          { return;
          }
          var e=document.createElement('div');
          e.setAttribute("id","__s_msg");
          e.style.display="none";
          document.body.appendChild(e);
          window.__e=e;
          })();
          window.__s_set_msg=function(a){
          window.__e.setAttribute("msg",a.toString()||"");
          }
          """
          _loadJsFmt="""
          var script = document.createElement('script');
          script.src = "{0}";
          document.body.appendChild(script);
          """
          _jquery_cdn="http://lib.sinaapp.com/js/jquery/1.7.2/jquery.min.js"
          _warpjsfmt="__s_set_msg({0})"
          class ExeJs(object):
          def __init__(self,driver,trytimes=10):
          from time import sleep
          self.driver=driver
          driver.execute_script(_init_js)
          while trytimes >0:
          try:
          self.msgNode=driver.find_element_by_id('__s_msg')
          break
          except Exception:
          sleep(1)
          trytimes -= 1
          if self.msgNode is None:
          raise Exception()
          def exeWrap(self,jsstr):
          """ jsstr 執(zhí)行后有返回值,返回值通過self.getMsg()獲取 """
          self.driver.execute_script(_warpjsfmt.format(jsstr))
          def loadJs(self,path):
          self.execute(_loadJsFmt.format(path))
          def loadJquery(self,path=_jquery_cdn):
          self.loadJs(path)
          def execute(self,jsstr):
          self.driver.execute_script(jsstr)
          def getMsg(self):
          return self.msgNode.get_attribute('msg')
          打開ipython上一個(gè)例子,獲取博客園首頁文章title列表
          from selenium import webdriver
          import exescript
          d=webdriver.PhantomJS("phantomjs")
          d.get("http://www.cnblogs.com/")
          exejs=exescript.ExeJs(d)
          exejs.exeWrap('$(".post_item").length')
          print exejs.getMsg()
          #out:
          """
          20
          """
          jsstr="""(function(){
          var r=[];
          $(".post_item").each(function(){
          var $this=$(this);
          var $h3=$this.find("h3");
          r.push($h3.text());
          });
          return r.join(',');})()"""
          exejs.exeWrap(jsstr)
          l=exejs.getMsg()
          for title in l.split(','):
          print title
          #out:
          """
          mac TeamTalk開發(fā)點(diǎn)點(diǎn)滴滴之一——DDLogic框架分解上
          The directfb backend was supported together with linux-fb backend in GTK+2.10
          Science上發(fā)表的超贊聚類算法
          功能齊全、效率一流的免費(fèi)開源數(shù)據(jù)庫導(dǎo)入導(dǎo)出工具(c#開發(fā),支持SQL server、SQLite、ACCESS三種數(shù)據(jù)  庫),每月借此處理數(shù)據(jù)5G以上
          企業(yè)級(jí)應(yīng)用框架(三)三層架構(gòu)之?dāng)?shù)據(jù)訪問層的改進(jìn)以及測試DOM的發(fā)布
          Unity3D 第一季 00 深入理解U3D開發(fā)平臺(tái)
          Welcome to Swift (蘋果官方Swift文檔初譯與注解二十一)---140~147頁(第三章--集合類型)
          appium簡明教程(11)——使用resource id定位
          SQL語句匯總(終篇)—— 表聯(lián)接與聯(lián)接查詢
          fopen警告處理方式
          AndroidWear開發(fā)之HelloWorld篇
          AMD and CMD are dead之KMD.js版本0.0.2發(fā)布
          SQL語句匯總(三)——聚合函數(shù)、分組、子查詢及組合查詢
          DevExpress GridControl功能總結(jié)
          ASP.NET之Jquery入門級(jí)別
          2014年前端面試經(jīng)歷
          grunt源碼解析:整體運(yùn)行機(jī)制&grunt-cli源碼解析
          跟用戶溝通,問題盡量分析清楚,以及解決問題
          ASP.NET之Ajax系列(一)
          算法復(fù)雜度分析
          """

          posted on 2014-09-30 10:03 順其自然EVO 閱讀(1332) 評(píng)論(0)  編輯  收藏 所屬分類: 測試學(xué)習(xí)專欄selenium and watir webdrivers 自動(dòng)化測試學(xué)習(xí)

          <2014年9月>
          31123456
          78910111213
          14151617181920
          21222324252627
          2829301234
          567891011

          導(dǎo)航

          統(tǒng)計(jì)

          常用鏈接

          留言簿(55)

          隨筆分類

          隨筆檔案

          文章分類

          文章檔案

          搜索

          最新評(píng)論

          閱讀排行榜

          評(píng)論排行榜

          主站蜘蛛池模板: 民和| 白玉县| 文成县| 堆龙德庆县| 中山市| 淮滨县| 长垣县| 正定县| 湖北省| 临桂县| 广宗县| 安阳县| 威远县| 海口市| 珠海市| 观塘区| 土默特左旗| 宁德市| 炎陵县| 盐津县| 合江县| 华宁县| 西峡县| 巴林右旗| 黎城县| 尉犁县| 加查县| 驻马店市| 安图县| 西和县| 平湖市| 美姑县| 建平县| 太白县| 竹溪县| 雷山县| 辽宁省| 龙海市| 子长县| 凤城市| 宁国市|