[簡單爬蟲]記錄博客流量-day day up

做了一個小工具,用於記錄我的csdn博客每天的流量變化,當程序運行的的時候捕獲到一場則發送郵件到我的郵箱,告知我來處理異常。每天的流量會記錄在csv文件中,可以使用pandas方便的獲取文件內容並繪圖。
用到的工具包括

  • requests
  • bs4(beautifulsoup4)
  • csv(buildin)
  • smtplib(buildin)

更詳細的內容請看代碼註釋

import requests   # 發送網絡請求
import bs4        # 解析網頁內容 
import csv        # 讀寫csv文件
from datetime import datetime
import smtplib    # 用於發送郵件
import time       # sleep

# csdn 博客地址,一下是我的地址
__url = "http://blog.csdn.net/pengjian444?skin=skin-yellow"


def send_mail(content, to_address='[email protected]'):
    try:
        content = "[博客記錄系統出現故障]: " + content
        # 這裏使用的是網易的smtp服務器
        # 默認使用ssl連接,默認的端口號是465
        smtp = smtplib.SMTP_SSL(" smtp.163.com", port=465)
        # qq 郵箱賬號
        username = "××××××"
        # 郵箱授權碼
        password = "××××××"
        smtp.login(username, password)
        smtp.sendmail(username,
                      to_address,
                      content)
    except Exception as base_e:
        log_line = "{}:{}".format(datetime.now(), str(base_e))
        print(log_line)
        with open('log.txt', 'a') as f:
            f.write(log_line)

def get_page_content(url):
    """
    獲取網頁內容
    """
    headers = {
        'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) '
                      'AppleWebKit/537.36 ('
                      'KHTML, like Gecko) Chrome/58.0.3029.81 '
                      'Safari/537.36',
        'Host'      : 'blog.csdn.net'
    }
    r = requests.get(url, headers=headers)
    if r.status_code != 200:
        return ""
    else:
        return r.text

def get_flux(page_content):
    if page_content is None:
        return None

    soup = bs4.BeautifulSoup(page_content, "html.parser")
    return int(soup.select("#blog_rank li span")[0].string[:-1])

def write_csv(flux_data, file_name='flux.csv'):
    """
    寫入csv文件
    :param flux_data:
    :param file_name:
    :return:
    """
    row = [str(datetime.now().date()), str(flux_data)]
    with open(file_name, 'a') as f:
        writer = csv.writer(f)
        writer.writerow(row)

if __name__ == '__main__':
    while True:
        try:
            content = get_page_content(url=__url)
            flux = get_flux(content)
            print(flux)
            write_csv(flux_data=flux)
        except Exception as e:
            send_mail(e)

        time.sleep(24 * 60 * 60)  # 每天記錄一次

這裏面綜合了一些很小的知識點,包括以下內容
+ 使用csv模塊讀寫csv文件
+ requests庫的簡單使用(發送get消息,設置headers)
+ 使用bs4解析網頁內容
+ 發送郵件

麻雀雖小,五臟俱全。希望大家能對大家有所幫助

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