CSDN博客原創訪問量日報工具

最近突然有點迷上攢博客,沒有什麼比有人看、排名上升更讓人興奮的了。可是日常總不能老盯着看增加了多少訪問量,像排名這種也沒辦法記住變化,故粗淺調查了一下beautifulsoup4這個python寫的html文件解析模塊,寫了一個小工具用來統計每篇原創文章的訪問量變化,在電腦上跑crontab,定時向公司郵箱發送報告。

# filename:CSDNvisitReport.py
# Author: BaoJunxian
# Date: 6/11/2018

import requests, bs4, json
from logging import info, basicConfig, INFO

basicConfig(level=INFO)

def infoGet(url, mainSelector, detailSelector, oldDic):
    response = requests.get(url).text
    soup = bs4.BeautifulSoup(response, 'html.parser')
    visit = int(soup.select('.grade-box dd[title]')[0].get('title'))
    rank = int(soup.select('.grade-box dl[title]')[0].get('title'))

    fileName = []
    fileVisit = []
    for i in soup.select(' '.join([mainSelector, detailSelector[0]])):
        text = i.getText()
        fileName.append(text.split('\n')[3].strip())

    temp = []
    for i in soup.select(' '.join([mainSelector, detailSelector[1]])):
        temp.append(int(i.getText().split(':')[1].strip()))
    for i in range(0, len(temp), 2):
        fileVisit.append(temp[i])

    dic = {fileName[i]: [fileVisit[i]] for i in range(len(fileName))}
    dic['visit'] = [visit]
    dic['rank'] = [rank]
    for i in dic.keys():
        if i in oldDic.keys():
            dic[i].append(dic[i][0] - oldDic[i][0])
        else:
            dic[i].append(dic[i][0])
    dic['rank'][1] = -dic['rank'][1]
    #排名數值增加,實際排名降低
    return dic

def reportGen(newDict):
    with open('visitReport.txt', 'w') as target:
        content = '''**************************
Today's summary is below:
    *Total Visit: %s   %s
    *Rank: %s   %s
**************************
Details:
            ''' % (newDict['visit'][0], newDict['visit'][1], \
                   newDict['rank'][0], newDict['rank'][1])
        target.write(content)
        target.write('\n')
        for i in newDict.keys():
            if i != 'visit' and i != 'rank':
                target.write(''.join([i.strip().ljust(45, ' '), \
                                      str(newDict[i][0]).ljust(5), \
                                      str(newDict[i][1]).ljust(7), '\n']))

def main():
    url = 'https://blog.csdn.net/qq_31331027?t=1'
    #對於CSDN獲取原創訪問量,直接修改url爲自己文章列表主頁即可
    detailSelector = ['h4 a', '.read-num']
    mainSelector = 'main .article-list'
    oldInfo = {}
    try:
        with open('visitData', 'r')as target:
            oldInfo = json.load(target)
    except:
        pass
    newDict = infoGet(url, mainSelector, detailSelector, oldInfo)
    reportGen(newDict)

    with open('visitData', 'w') as target:
        json.dump(newDict, target)

if __name__ == '__main__':
    main()

這是主要的運行程序,會生成當天的統計數據,主要記錄數據爲:總閱讀量、總排名、每篇原創的閱讀量以及這幾個數據跟前一天對比的漲幅(跌幅)。在對這幾類數據進行處理時,將數據名稱作爲key,數值value用list表示,list[0]表示當前數量,list[1]表示跟前一天list[0]數值上的差值。運行程序生成兩個文件,一個是當日統計數據的字典,json形式保存(visitData),還有一個直接是visitReport.txt,記錄報表內容,直接用於crontab發送郵件的文本內容(crontab的執行目錄默認是從cron計劃用戶的家目錄下面的,因此這兩個visitX文件默認生成在用戶家目錄下面)。
其次,編寫腳本自動執行程序以及發送郵件的命令(發送郵件我用的是linux,安裝sendemail):

# filename:autoReport.py
import os,time
os.system('python /home/stanpao/python/CSDNreport/CSDNvisitReport.py')
time.sleep(120)
os.system('sendemail -s smtp.qq.com -f [email protected]\
         -t [email protected] -u "CSDN Daily Report" -xu [email protected]\
         -xp password -o message-content-type=text\
         message-file=visitReport.txt message-charset=utf-8')

值得說明sendemail中幾個參數:-s 是smtp服務器域名,如果qq就是smtp.qq.com,如果是163就是smtp.163.com;-f 發件人; -t 收件人; -u 郵件標題; -xu 發件人郵箱 ; -xp 發件郵箱密碼 ; -o指定一些郵件內容參數: message-content-type – 郵件文本類型,message-file – 文本文件,message-charset – 郵件內容編碼形式。至此,已經能夠進行正常的report。
但是,要完全自動化發送每日報道,還需要地址crontab由系統自行完成:

0 9 * * * python /home/stanpao/python/CSDNreport/autoReport.py

以上,完全告終。收到郵件效果如下。其中,第一個數字爲當前值,後一個數字爲對比前一天的浮動數值。
代碼略有粗糙,也沒什麼複用價值,重構也沒啥必要,圖個實用好玩,還望客官輕點~我還是個孩子~
這裏寫圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章