最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

在Python中使用CasperJS獲取JS渲染生成的HTML內(nèi)容的教程

 更新時間:2015年04月09日 10:15:12   作者:Ihavegotyou  
這篇文章主要介紹了在Python中使用CasperJS獲取JS渲染生成的HTML內(nèi)容的教程,需要先用JavaScript創(chuàng)建一個接口文件,需要的朋友可以參考下

文章摘要:其實這里casperjs與python沒有直接關(guān)系,主要依賴casperjs調(diào)用phantomjs webkit獲取html文件內(nèi)容。長期以來,爬蟲抓取 客戶端javascript渲染生成的html頁面 都極為 困難, Java里面有 HtmlUnit, 而Python里,我們可以使用獨立的跨平臺的CasperJS。

    創(chuàng)建site.js(接口文件,輸入:url,輸出:html file)  

   //USAGE: E:\toolkit\n1k0-casperjs-e3a77d0\bin>python casperjs site.js --url=http://spys.ru/free-proxy-list/IE/ --outputfile='temp.html' 
     
    var fs = require('fs'); 
    var casper = require('casper').create({ 
     pageSettings: { 
     loadImages: false,     
     loadPlugins: false,    
     userAgent: 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1847.137 Safari/537.36 LBBROWSER' 
    }, 
    logLevel: "debug",//日志等級 
    verbose: true  // 記錄日志到控制臺 
     }); 
    var url = casper.cli.raw.get('url'); 
    var outputfile = casper.cli.raw.get('outputfile'); 
    //請求頁面 
    casper.start(url, function () { 
    fs.write(outputfile, this.getHTML(), 'w'); 
    }); 
     
    casper.run(); 

    python 代碼, checkout_proxy.py      

 import json 
    import sys 
    #import requests 
    #import requests.utils, pickle 
    from bs4 import BeautifulSoup 
    import os.path,os 
    import threading 
    #from multiprocessing import Process, Manager 
    from datetime import datetime 
    import traceback 
    import logging 
    import re,random 
    import subprocess 
    import shutil 
    import platform 
      
     
     
     
    output_file = os.path.join(os.path.dirname(os.path.realpath(__file__)),'proxy.txt') 
    global_log = 'http_proxy' + datetime.now().strftime('%Y-%m-%d') + '.log' 
    if not os.path.exists(os.path.join(os.path.dirname(os.path.realpath(__file__)),'logs')): 
      os.mkdir(os.path.join(os.path.dirname(os.path.realpath(__file__)),'logs')) 
    global_log = os.path.join(os.path.dirname(os.path.realpath(__file__)),'logs',global_log) 
     
    logging.basicConfig(level=logging.DEBUG,format='[%(asctime)s] [%(levelname)s] [%(module)s] [%(funcName)s] [%(lineno)d] %(message)s',filename=global_log,filemode='a') 
    log = logging.getLogger(__name__)  
    #manager = Manager() 
    #PROXY_LIST = manager.list() 
    mutex = threading.Lock() 
    PROXY_LIST = [] 
     
     
    def isWindows(): 
      if "Windows" in str(platform.uname()): 
      return True 
      else: 
      return False 
     
     
    def getTagsByAttrs(tagName,pageContent,attrName,attrRegValue): 
      soup = BeautifulSoup(pageContent)                                                 
      return soup.find_all(tagName, { attrName : re.compile(attrRegValue) }) 
     
     
    def getTagsByAttrsExt(tagName,filename,attrName,attrRegValue): 
      if os.path.isfile(filename): 
      f = open(filename,'r')    
      soup = BeautifulSoup(f) 
      f.close() 
      return soup.find_all(tagName, { attrName : re.compile(attrRegValue) }) 
      else: 
      return None 
     
     
    class Site1Thread(threading.Thread): 
      def __init__(self,outputFilePath): 
        threading.Thread.__init__(self) 
      self.outputFilePath = outputFilePath 
      self.fileName = str(random.randint(100,1000)) + ".html" 
      self.setName('Site1Thread') 
      
      def run(self): 
      site1_file = os.path.join(os.path.dirname(os.path.realpath(__file__)),'site.js') 
      site2_file = os.path.join(self.outputFilePath,'site.js') 
      if not os.path.isfile(site2_file) and os.path.isfile(site1_file): 
        shutil.copy(site1_file,site2_file) 
      #proc = subprocess.Popen(["bash","-c", "cd %s && ./casperjs site.js --url=http://spys.ru/free-proxy-list/IE/ --outputfile=%s" % (self.outputFilePath,self.fileName) ],stdout=subprocess.PIPE) 
      if isWindows(): 
        proc = subprocess.Popen(["cmd","/c", "%s/casperjs site.js --url=http://spys.ru/free-proxy-list/IE/ --outputfile=%s" % (self.outputFilePath,self.fileName) ],stdout=subprocess.PIPE) 
      else: 
        proc = subprocess.Popen(["bash","-c", "cd %s && ./casperjs site.js --url=http://spys.ru/free-proxy-list/IE/ --outputfile=%s" % (self.outputFilePath,self.fileName) ],stdout=subprocess.PIPE) 
      out=proc.communicate()[0] 
      htmlFileName = '' 
      #因為輸出路徑在windows不確定,所以這里加了所有可能的路徑判斷 
      if os.path.isfile(self.fileName): 
        htmlFileName = self.fileName 
      elif os.path.isfile(os.path.join(self.outputFilePath,self.fileName)): 
        htmlFileName = os.path.join(self.outputFilePath,self.fileName) 
      elif os.path.isfile(os.path.join(os.path.dirname(os.path.realpath(__file__)),self.fileName)): 
        htmlFileName = os.path.join(os.path.dirname(os.path.realpath(__file__)),self.fileName)  
      if (not os.path.isfile(htmlFileName)): 
        print 'Failed to get html content from http://spys.ru/free-proxy-list/IE/' 
        print out 
        sys.exit(3)  
      mutex.acquire() 
      PROXYList= getTagsByAttrsExt('font',htmlFileName,'class','spy14$') 
      for proxy in PROXYList: 
        tdContent = proxy.renderContents() 
        lineElems = re.split('[<>]',tdContent) 
        if re.compile(r'\d+').search(lineElems[-1]) and re.compile('(\d+\.\d+\.\d+)').search(lineElems[0]): 
        print lineElems[0],lineElems[-1] 
        PROXY_LIST.append("%s:%s" % (lineElems[0],lineElems[-1])) 
      mutex.release() 
      try: 
        if os.path.isfile(htmlFileName): 
        os.remove(htmlFileName) 
      except: 
        pass 
     
    if __name__ == '__main__': 
      try: 
      if(len(sys.argv)) < 2: 
        print "Usage:%s [casperjs path]" % (sys.argv[0]) 
        sys.exit(1)  
      if not os.path.exists(sys.argv[1]): 
        print "casperjs path: %s does not exist!" % (sys.argv[1]) 
        sys.exit(2)  
      if os.path.isfile(output_file): 
        f = open(output_file) 
        lines = f.readlines() 
        f.close 
        for line in lines: 
        PROXY_LIST.append(line.strip()) 
      thread1 = Site1Thread(sys.argv[1]) 
      thread1.start() 
      thread1.join() 
       
      f = open(output_file,'w') 
      for proxy in set(PROXY_LIST): 
        f.write(proxy+"\n") 
      f.close() 
      print "Done!" 
      except SystemExit: 
      pass 
      except: 
        errMsg = traceback.format_exc() 
        print errMsg 
        log.error(errMsg) 

相關(guān)文章

  • Python實現(xiàn)爬蟲IP負(fù)載均衡和高可用集群的示例代碼

    Python實現(xiàn)爬蟲IP負(fù)載均衡和高可用集群的示例代碼

    做大型爬蟲項目經(jīng)常遇到請求頻率過高的問題,這里需要說的是使用爬蟲IP可以提高抓取效率,本文主要介紹了Python實現(xiàn)爬蟲IP負(fù)載均衡和高可用集群的示例代碼,感興趣的可以了解一下
    2023-12-12
  • 感知器基礎(chǔ)原理及python實現(xiàn)過程詳解

    感知器基礎(chǔ)原理及python實現(xiàn)過程詳解

    這篇文章主要介紹了感知器基礎(chǔ)原理及python實現(xiàn)過程詳解,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
    2019-09-09
  • python單例模式獲取IP代理的方法詳解

    python單例模式獲取IP代理的方法詳解

    在使用python對網(wǎng)頁進(jìn)程訪問時,以防被禁止,可用使用代理IP的方法減少被禁的可能,下面這篇文章主要給大家介紹了關(guān)于python單例模式獲取IP代理的相關(guān)資料,需要的朋友可以參考借鑒,下面來一起看看吧
    2018-09-09
  • 在python3中使用shuffle函數(shù)要注意的地方

    在python3中使用shuffle函數(shù)要注意的地方

    今天小編就為大家分享一篇在python3中使用shuffle函數(shù)要注意的地方,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-02-02
  • Python中 傳遞值 和 傳遞引用 的區(qū)別解析

    Python中 傳遞值 和 傳遞引用 的區(qū)別解析

    這篇文章主要介紹了Python中 傳遞值 與 傳遞引用 的區(qū)別解析,非常不錯,具有參考借鑒價值,需要的朋友參考下吧
    2018-02-02
  • Pytest框架之fixture詳解(二)

    Pytest框架之fixture詳解(二)

    本文詳細(xì)講解了Pytest框架之fixture,文中通過示例代碼介紹的非常詳細(xì)。對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2022-06-06
  • python 將數(shù)據(jù)保存為excel的xls格式(實例講解)

    python 將數(shù)據(jù)保存為excel的xls格式(實例講解)

    下面小編就為大家分享一篇python 將數(shù)據(jù)保存為excel的xls格式(實例講解),具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2018-05-05
  • 40個你可能不知道的Python技巧附代碼

    40個你可能不知道的Python技巧附代碼

    這篇文章主要介紹了40個你可能不知道的Python的特點和技巧,需要的朋友可以參考下
    2020-01-01
  • Python實現(xiàn)合并PDF文件的三種方式

    Python實現(xiàn)合并PDF文件的三種方式

    在處理多個 PDF 文檔時,頻繁地打開關(guān)閉文件會嚴(yán)重影響效率,因此我們可以先將這些PDF文件合并起來再操作,本文將分享3種使用 Python 合并 PDF 文件的實現(xiàn)方法,希望對大家有所幫助
    2023-11-11
  • python實現(xiàn)人機(jī)對戰(zhàn)的井字棋游戲

    python實現(xiàn)人機(jī)對戰(zhàn)的井字棋游戲

    這篇文章主要為大家詳細(xì)介紹了python實現(xiàn)人機(jī)對戰(zhàn)的井字棋游戲,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2022-04-04

最新評論

民勤县| 丰城市| 兴和县| 崇州市| 固原市| 永清县| 高唐县| 米脂县| 贵德县| 青海省| 淳化县| 靖远县| 宽甸| 视频| 榆中县| 玛纳斯县| 乐东| 当雄县| 岳池县| 稻城县| 贵溪市| 大名县| 牟定县| 武隆县| 利津县| 安庆市| 汾西县| 轮台县| 潢川县| 崇文区| 静海县| 萍乡市| 深水埗区| 安顺市| 南安市| 延庆县| 新余市| 百色市| 怀远县| 神木县| 丰原市|