在Python中使用CasperJS獲取JS渲染生成的HTML內(nèi)容的教程
文章摘要:其實(shí)這里casperjs與python沒(méi)有直接關(guān)系,主要依賴casperjs調(diào)用phantomjs webkit獲取html文件內(nèi)容。長(zhǎng)期以來(lái),爬蟲(chóng)抓取 客戶端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實(shí)現(xiàn)爬蟲(chóng)IP負(fù)載均衡和高可用集群的示例代碼
做大型爬蟲(chóng)項(xiàng)目經(jīng)常遇到請(qǐng)求頻率過(guò)高的問(wèn)題,這里需要說(shuō)的是使用爬蟲(chóng)IP可以提高抓取效率,本文主要介紹了Python實(shí)現(xiàn)爬蟲(chóng)IP負(fù)載均衡和高可用集群的示例代碼,感興趣的可以了解一下2023-12-12
感知器基礎(chǔ)原理及python實(shí)現(xiàn)過(guò)程詳解
這篇文章主要介紹了感知器基礎(chǔ)原理及python實(shí)現(xiàn)過(guò)程詳解,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-09-09
在python3中使用shuffle函數(shù)要注意的地方
今天小編就為大家分享一篇在python3中使用shuffle函數(shù)要注意的地方,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-02-02
python 將數(shù)據(jù)保存為excel的xls格式(實(shí)例講解)
下面小編就為大家分享一篇python 將數(shù)據(jù)保存為excel的xls格式(實(shí)例講解),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-05-05
Python實(shí)現(xiàn)合并PDF文件的三種方式
在處理多個(gè) PDF 文檔時(shí),頻繁地打開(kāi)關(guān)閉文件會(huì)嚴(yán)重影響效率,因此我們可以先將這些PDF文件合并起來(lái)再操作,本文將分享3種使用 Python 合并 PDF 文件的實(shí)現(xiàn)方法,希望對(duì)大家有所幫助2023-11-11
python實(shí)現(xiàn)人機(jī)對(duì)戰(zhàn)的井字棋游戲
這篇文章主要為大家詳細(xì)介紹了python實(shí)現(xiàn)人機(jī)對(duì)戰(zhàn)的井字棋游戲,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-04-04

