背景:
筆者因為需要在 www.kindle114.com 上分享一些圖書,鑒于各種網盤神馬的,都會把涉及版權的分享給失效了,總是換分享連接很麻煩,所以不得已只能通過郵件來傳播知識,這就需要每天去看回帖的郵箱,一一發送,甚是麻煩。用一個python的腳本去掃描這些頁面,把郵箱地址抓出來后自動發送才是懶人應該做的事情。
實現過程:
需要用crontab來實現每天定時執行這個腳本。
腳本一共分三部分:
1. 遍歷指定帖子的所有回帖頁,抓取Email格式的字符串,遇到某些情況就終止掃描
2. 比對過去發送過的列表,如果是新出現的則加入發送列表中
3. 將發送列表用python的email功能發送出去,并且帶上附件
可以改進的地方:
1. 記錄下每次掃描的終點,下次從這個位置掃描,避免重復掃描的浪費
2. 將URL和附件做成字典,可以靈活發送
3. 做成一個在線系統來維護這個數據和列表
注意點:
1. python的sendmail,發送列表要用list類型的
2. 如果是QQ郵箱,要把郵箱的獨立密碼去掉(我也不知道如果不去掉應該怎么去驗證),否則會出現驗證失敗的錯誤
3. 可能有人會因為隱私原因,把郵箱地址寫成怪怪的樣子,那我就沒轍了...
4 本文只是拋磚引玉,論壇形式千變萬化,需要靈活修改腳本來實現網頁抓取
5. 鑒于現在出版物粗糙的太多了,所以想先預覽一下合情合理。如果覺得電子書或者視頻有價值,請去電影院看電影或購買正版書籍,寫這個短短文章都需要花費時間和精力,何況是寫書和拍片,人家就是靠這個謀生。
#!/usr/bin/pythonimport sys, urllib, refrom email.Header import Headerfrom email.MIMEText import MIMETextfrom email.MIMEMultipart import MIMEMultipartimport smtplib, datetimedef sendMail(toWho,fromWho,bookName,text): msg = MIMEMultipart() ## fill your BT torrent or eBook ... att = MIMEText(open(bookName, 'rb').read(), 'base64', 'gb2312') att["Content-Type"] = 'application/octet-stream' att["Content-Disposition"] = 'attachment; filename="Redis_shejiyushixian.mobi"' msg.attach(att) msg['from'] = fromWho msg['subject'] = Header(bookName + '(' + str(datetime.date.today()) + ')','gb2312') msg.attach(MIMEText(text)) server = smtplib.SMTP('smtp.qq.com') ## fill your QQ number and passWord server.login('1234567','xxxxxxxxxxxx') error=server.sendmail(msg['from'],toWho,msg.as_string()) server.close PRint errordicSave = {}for line in open("log"): dicSave[line.rstrip()] = 1dic = {}preDic = {}## grep Email format stringpattern = re.compile(r'[_.0-9a-z-]+@(?:[0-9a-z][0-9a-z-]+.)+[a-z]{2,3}/b')## please enhance this script to mark stop page as next start pagefor x in range(1,100): ## fill forum url which need scan url="http://www.kindle114.com/thread-4567-%d-1.html" % x print "%s" % url wp = urllib.urlopen(url) content = wp.read() ## get mail list m = pattern.findall(content) stopFlag = 1 for i in m: ## if page is duplicate means scan is wasting time and need stop if i not in preDic: stopFlag = 0 ## only new mail address is needed to deliver if i not in dicSave: dic[i] = 1 if stopFlag == 1: print "Scan Page Over %d/n" % x break preDic = mmailList = []## write deliver mail address to log to avoid duplicate deliver in next runfile_object = open("log", 'a+')for k,v in dic.items(): print k mailList.append(k) file_object.write(k+"/n")file_object.close()if mailList: print "Delivering.../n"; sendMail(mailList,'77167680@qq.com','Redis_shejiyushixian.mobi','What are you interested in ?') print "Deliver is completed.../n";else: print "Mail List is empty/n";
新聞熱點
疑難解答