1. 程式人生 > 實用技巧 >Python爬取熱搜存入資料庫並且還能定時傳送郵件!!!

Python爬取熱搜存入資料庫並且還能定時傳送郵件!!!

一、前言

微博熱搜榜每天都會更新一些新鮮事,但是自己處於各種原因,肯定不能時刻關注著微博,為了與時代接軌,接受最新資訊,就尋思著用Python寫個定時爬取微博熱搜的並且傳送QQ郵件的程式,這樣每天可以在不開啟微博的情況下,時刻掌握著微博的最新動態資訊。

廢話不多說,下面直接上程式碼以及詳細思路。

二、程式碼及思路

(1)首先肯定是對微博熱搜進行爬取,這並不難,是個非常簡單的爬蟲。

def getHTML(url):
    
    headers={
        "User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.66 Safari/537.36",
    } # 瀏覽器請求頭
    r = requests.get(url, headers = headers) # 向該網頁發起請求
    # 如果返回的響應碼是200 則表示請求成功,否則返回“獲取失敗”
    if r.status_code == 200:
        r.encoding = r.apparent_encoding 
        return r.text
    else:
        return "獲取失敗"

(2)接下來對返回的原始碼進行解析,這邊我用的是xpath。

def parseHTML(html):
    html = etree.HTML(html)
    content = html.xpath('//div[@class="data"]//table//tr[position()>1]/td[@class="td-02"]//a/text()')
    return content

(3)獲取到需要的資料之後,就將它們存入資料庫。第一步就是要連線上資料庫,然後建立對應的表格儲存資料。

def toDB(content):

    db = pymysql.connect('localhost', 'root', '密碼', 'lqj', charset="utf8")
    cursor = db.cursor()
    dt = time.strftime("%Y-%m-%d %X")
    sql = '''
      create table if not exists wb_Hotdata(
          日期 datetime, 
          熱搜 varchar(100) primary key )
         
      '''
    cursor.execute(sql)
    for item in content:
        sql1 = "INSERT IGNORE INTO wb_Hotdata(日期,熱搜) VALUES (%s,%s)"
        cursor.execute(sql1,(dt,item))
        db.commit()
    print("資料插入成功")
    cursor.close()
    db.close()

(4)下一步,也是整篇文章的靈魂,就是講熱搜定時傳送到自己的郵箱,這樣就能及時獲取最新資訊。

def sendMail(contents):
    mailBox = '傳送郵箱'  
    password = '郵箱授權碼'  

    to_mail = '接收郵箱'  # 接收郵箱

    mailhost = 'smtp.qq.com'  # qq郵箱的smtp地址
    qqmail = smtplib.SMTP()  # 建立SMTP物件
    qqmail.connect(mailhost, 25)  
    qqmail.login(from_addr, password)  
    dt = time.strftime("%Y-%m-%d %X")
    data  = ''
    for content in contents:  
        data += '當前時間' + dt + '\n' + '熱搜:' + content + '\n'
        data += '=============================\n' #分割線

    msg = MIMEText(data, 'plain', 'utf-8')
    msg['subject'] = Header("即時微博熱搜", 'utf-8')

    try:
        qqmail.sendmail(mailBox, to_mail, msg.as_string())
        print('傳送成功!')
    except:
        print('傳送失敗!')
    qqmail.quit()

(5)最後一步,就是要實現定時傳送這個功能了,這邊我使用的是schedule模組。

def main():
    html = getHTML("https://s.weibo.com/top/summary")
    contents = parseHTML(html)
    toDB(contents)
    sendMail(contents)
  
schedule.every().day.at("10:30").do(main) # 每天早上10:30執行main函式
while True:
    schedule.run_pending()
    time.sleep(1)

效果圖:


這樣看起來是不是很簡單明瞭,並且不需要時刻開啟微博,自己指定任意時間就能收到一手資訊,與“out了”說拜拜!



三、結語

當然,這只是微博熱搜,如果需要其他資訊,也可以獲取其他平臺的資料,定時傳送到郵箱中,或者網站發生變動,也可以第一時間提醒你,非常的方便!

想要獲取更多Python學習資料可以加QQ:2955637827私聊或加Q群630390733大家一起來學習討論吧!

本文的文字及圖片來源於網路,僅供學習、交流使用,不具有任何商業用途,如有問題請及時聯絡我們以作處理