phantomjs + python 打造一個微信機器人
1.前奏
媳婦公司不能上網,但經常需要在公眾號上找一些文章做一些參考,需要的時候就把文章鏈接分享給我,然后我在瀏覽器打開網頁,一點點復制過來粘貼到word中,遇到圖片更悲催,還得手動調整大小。是不是感覺自己的碼農職稱受到了挑戰……,某一天看到一篇基於C#.NET的高端智能化網絡爬蟲(二)(攻破攜程網),才發現了PhantomJS,由此解放了我復制粘貼的雙手
2.介紹
PhantomJS
PhantomJS是一個基於webkit的JavaScript API。它使用QtWebKit作為它核心瀏覽器的功能,使用webkit來編譯解釋執行JavaScript代碼。任何你可以在基於webkit瀏覽器做的事情,它都能做到。它不僅是個隱形的瀏覽器,提供了諸如CSS選擇器、支持Web標准、DOM操作、JSON、HTML5、Canvas、SVG等,同時也提供了處理文件I/O的操作,從而使你可以向操作系統讀寫文件等。PhantomJS的用處可謂非常廣泛,諸如網絡監測、網頁截屏、無需瀏覽器的 Web 測試、頁面訪問自動化等。。。
python
python當歌,人生幾何。。。
itchat
itchat是一個開源的微信個人號接口,使用python調用微信從未如此簡單。使用不到三十行的代碼,你就可以完成一個能夠處理所有信息的微信機器人。當然,該api的使用遠不止一個機器人,更多的功能等着你來發現,比如這些。該接口與公眾號接口itchatmp共享類似的操作方式,學習一次掌握兩個工具。如今微信已經成為了個人社交的很大一部分,希望這個項目能夠幫助你擴展你的個人的微信號、方便自己的生活。摘自官方文檔
各種文檔地址
PhantomJS官方地址:http://phantomjs.org/。
PhantomJS官方API:http://phantomjs.org/api/。
PhantomJS官方示例:http://phantomjs.org/examples/。
PhantomJS GitHub:https://github.com/ariya/phantomjs/。
python廖雪峰教程
圖靈機器人
3.話不多說,代碼為證
第一步利用PhantomJs將網頁生成pdf的功能把需要的文章保存好
//創建webpage模塊,用來請求並生成pdf
var page = require('webpage').create();
//創建system模塊,用來獲取外部傳遞的參數
var system = require('system');
//設置編碼方式
phantom.outputEncoding = 'gb2312';
page.onError = function (msg, trace) {
console.log(msg);
var msgStack = ['PHANTOM ERROR: ' + msg];
if (trace && trace.length) {
msgStack.push('TRACE:');
trace.forEach(function (t) {
msgStack.push(' -> ' +
(t.file || t.sourceURL) + ': ' + t.line +
(t.function ? ' (in function ' + t.function + ')' : ''));
});
}
console.error(msgStack.join('\n'));
phantom.exit(1);
};
if (system.args.length == 1) {
console.log('請輸入文章地址');
phantom.exit();
} else {
var url = system.args[1];
var filename = '';
if (system.args.length == 3) {
filename = system.args[2];
}
//地址檢測
if (url.indexOf('http') == -1) {
url = 'http://' + url;
}
page.viewportSize = { width: 600, height: 20 };//設置圖片大小 height自動適應
//===================pdf頁面設置=====================
page.settings.userAgent = 'Mozilla/5.0 AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.117 Safari/537.36';
page.zoomFactor = 1;//頁面縮放比例
page.settings.loadImages = true;//頁面加載圖片
//format :A4 紙,可以設置 "5in*7.5in", "10cm*20cm", "Letter" 等
//orientation :紙方向是豎着的,或者 landscape
//margin :與紙四邊間距,可自定義,也可詳細設置 margin : { left: ‘0.8cm‘, top : ‘0.8cm‘, right : ‘0.8cm‘, bottom : ‘0.8cm‘ }
//設置頁面格式
//page.paperSize = { format: 'A4', orientation: 'portrait', margin: '0.8cm' };
//===================pdf頁面設置=====================
page.open(url, function (status) {//加載頁面
console.log('抓取結果:' + status);
//利用page的evaluate獲取網頁的title
var title = page.evaluate(function () {
return document.title;
});
//去除特殊字符
var title = title
.replace('|', '').replace('\\', '').replace('/', '').replace(':', '').replace('*', '')
.replace('?', '').replace('"', '').replace('<', '').replace('>', '');
filename = filename.length > 0 ? filename : title;
var wait = 200;
//是否是微信地址
if (url.indexOf("mp.weixin.qq.com") > -1) {
//設置5秒是等待微信中圖片完全加載出來,具體可調整
wait = 5000;
//加載微信圖片
//includeJs 側重網絡js文件,尤其在引入jQuery等第三方庫
//injectJs 側重本地的js文件,與libraryPath掛購
page.injectJs('replaceimage.js', function () {
var titlexx = page.evaluate(function () {
return document.title;
});
});
console.log(title);
console.log('等待5秒生成pdf');
}
//等待頁面執行完js后在進行生成
window.setTimeout(function () {
page.render(filename + '.pdf');
console.log('pdf生成成功:' + title);
phantom.exit();
}, wait);
});
}
由於微信頁面對請求refer有限制,頁面中的圖片是展現不出來的,replaceimage.js是將微信頁面中的圖片加載出來
window.onload = function change() {
var metas = document.getElementsByTagName('meta');
metas[0].insertAdjacentHTML('beforeBegin', "<meta name='referrer' content='never'>");
var body = document.getElementById("activity-detail");
//圖片請求設置cookie
body.insertAdjacentHTML("beforeBegin", "<image style='display: none' src='http://mmbiz.qpic.cn/mmbiz_png/pmBoItic0ByggW4X5ACKS5rfIfB1VM7RIic0TA9no7a0pRFHLcBibJX8VAyxUw756hHibQccolNUjRbKviaT3QzpwJA/0?wx_fmt=png' alt='bg'/>");
//替換img圖片鏈接
var imglist = body.getElementsByTagName('IMG')
for (i = 0; i < imglist.length; i++) {
if (imglist[i].getAttribute('src')!=null && imglist[i].getAttribute('src').length > 0 && imglist[i].getAttribute('src').indexOf("mmbiz.qpic.cn") > -1) {
imglist[i].setAttribute('src', "http://read.html5.qq.com/image?src=forum&q=5&r=0&imgflag=7&imageUrl=" + imglist[i].getAttribute('src'));
}
if (imglist[i].getAttribute('data-src')!=null && imglist[i].getAttribute('data-src').length > 0 && imglist[i].getAttribute('data-src').indexOf("mmbiz.qpic.cn") > -1) {
imglist[i].setAttribute('src', "http://read.html5.qq.com/image?src=forum&q=5&r=0&imgflag=7&imageUrl=" + imglist[i].getAttribute('data-src'));
}
if (imglist[i].getAttribute('data-s')!=null && imglist[i].getAttribute('data-s').length > 0) {
var w=imglist[i].getAttribute('data-s').split(",")[0];
var h=imglist[i].getAttribute('data-s').split(",")[1];
imglist[i].setAttribute('width',h);
imglist[i].setAttribute('height',w);
}
}
//替換背景圖片
var sectionlist = document.querySelectorAll('section')
for (j = 0; j < sectionlist.length; j++) {
var newhtml = sectionlist[j].style.backgroundImage.replace("http://mmbiz.qpic.cn", "http://read.html5.qq.com/image?src=forum&q=5&r=0&imgflag=7&imageUrl=http://mmbiz.qpic.cn");
sectionlist[j].style.backgroundImage = newhtml;
}
}
執行命令,phantomjs xx.js "http://mp.weixin.qq.com/s/zFdPBDJcGsTbQgKGogLzyw"
第二步利用Python結合itchat接收消息,調用phantomjs生成pdf
#-*-coding:utf-8-*-
import itchat,time
from itchat.content import *
import requests,json,sys
import hashlib
import HTMLParser
import re
import os
from sys import argv
#接收文本消息,提取網址
@itchat.msg_register([TEXT])
def text_reply(msg):
# 將正則表達式編譯成Pattern對象
pattern = re.compile(r"http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*,]|(?:%[0-9a-fA-F][0-9a-fA-F]))+", re.IGNORECASE)
# 使用Pattern匹配文本,獲得匹配結果,無法匹配時將返回None
match = pattern.match(msg['Text'])
if match:
# 使用Match獲得分組信息
print match.group()
filename=int(time.time())
urltopdf(msg['FromUserName'],match.group(),str(filename))
#獲取分享的文章地址
@itchat.msg_register([SHARING])
def sharingtopdf(msg):
filename=u''+'"'+msg['Text']+'"'
urltopdf(msg['FromUserName'],msg['Url'],filename)
@itchat.msg_register(PICTURE,RECORDING,ATTACHMENT,VIDEO)
def download_files(msg):
msg['Text'](msg['FileName'])
return '@%s@%s' % ({'Picture': 'img', 'Video': 'vid'}.get(msg['Type'], 'fil'), msg['FileName'])
@itchat.msg_register(FRIENDS)
def add_friend(msg):
itchat.add_friend(**msg['Text'])
itchat.send_msg('Nice to meet you!',msg['RecommentInfo']['UserName'])
@itchat.msg_register(TEXT,isGroupChat=True)
def text_reply(msg):
if msg['isAt']:
itchat.send(u'@%s\u2005I received: %s' % (msg['ActualNickName'], msg['Content']), msg['FromUserName'])
def urltopdf(touser,url,filename):
#切換到phantomjs目錄
os.chdir('D:\sourcecode\htmlsource\phantomjs')
#文件名
filename= filename.replace('|', '').replace('\\', '').replace('/', '').replace(':', '').replace('*', '').replace('?', '').replace('"', '').replace('<', '').replace('>', '')
itchat.send(u'正在生成pdf,請稍等',touser)
#解碼url
html_parser = HTMLParser.HTMLParser()
article_url = html_parser.unescape(url)
#執行
#python中文編碼問題解決方式
cmd_method="phantomjs loadpage.js %s %s" % ('"'+url+'"',filename)
os.system(cmd_method.encode('gb2312'))
#發送
all_file_path="D:\\sourcecode\\htmlsource\\phantomjs\\%s.pdf" % (filename)
#py2.7版本需要下載fields.py 並覆蓋
#安裝目錄下 requests\packages\urllib3
itchat.send_file(all_file_path,touser)
itchat.auto_login(enableCmdQR=True,hotReload=True)
itchat.run()