在Python中使用CasperJS獲取JS渲染生成的HTML內(nèi)容的教程
文章摘要:其實(shí)這里casperjs與python沒有直接關(guān)系,主要依賴casperjs調(diào)用phantomjs webkit獲取html文件內(nèi)容。長(zhǎng)期以來(lái),爬蟲抓取 客戶端javascript渲染生成的html頁(yè)面 都極為 困難, Java里面有 HtmlUnit, 而Python里,我們可以使用獨(dú)立的跨平臺(tái)的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",//日志等級(jí)
verbose: true // 記錄日志到控制臺(tái)
});
var url = casper.cli.raw.get('url');
var outputfile = casper.cli.raw.get('outputfile');
//請(qǐng)求頁(yè)面
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 = ''
#因?yàn)檩敵雎窂皆趙indows不確定,所以這里加了所有可能的路徑判斷
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如何使用k-means方法將列表中相似的句子歸類
這篇文章主要介紹了Python如何使用k-means方法將列表中相似的句子聚為一類,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-08-08
對(duì)Python實(shí)現(xiàn)累加函數(shù)的方法詳解
今天小編就為大家分享一篇對(duì)Python實(shí)現(xiàn)累加函數(shù)的方法詳解,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來(lái)看看吧2019-01-01
Sublime Text3最新激活注冊(cè)碼分享適用2020最新版 親測(cè)可用
這篇文章主要介紹了Sublime Text3最新激活注冊(cè)碼分享親測(cè)3211可用2020-11-11
如何將numpy二維數(shù)組中的np.nan值替換為指定的值
這篇文章主要介紹了將numpy二維數(shù)組中的np.nan值替換為指定的值操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-05-05
淺談python連續(xù)賦值可能引發(fā)的錯(cuò)誤
今天小編就為大家分享一篇淺談python連續(xù)賦值可能引發(fā)的錯(cuò)誤,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來(lái)看看吧2018-11-11
django創(chuàng)建自定義模板處理器的實(shí)例詳解
這篇文章主要介紹了django創(chuàng)建自定義模板處理器的實(shí)例詳解的相關(guān)資料,這里說(shuō)明了如何需要django模板處理器及實(shí)現(xiàn)方法,希望大家能理解掌握這部分內(nèi)容,需要的朋友可以參考下2017-08-08
詳解如何使用Python實(shí)現(xiàn)復(fù)制粘貼的功能
pandas?里面有一個(gè)?pd.read_clipboard?函數(shù),可以根據(jù)你復(fù)制的內(nèi)容生成DataFrame。本文就利用這個(gè)函數(shù)實(shí)現(xiàn)復(fù)制粘貼的功能,感興趣的可以了解一下2023-01-01
對(duì)tensorflow中cifar-10文檔的Read操作詳解
今天小編就為大家分享一篇對(duì)tensorflow中cifar-10文檔的Read操作詳解,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來(lái)看看吧2020-02-02
python實(shí)現(xiàn)與Oracle數(shù)據(jù)庫(kù)交互操作示例
這篇文章主要為大家介紹了python實(shí)現(xiàn)與Oracle數(shù)據(jù)庫(kù)交互操作示例,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家,多多進(jìn)步,早日升職加薪2021-10-10

