Python 的輕鬆閲讀
Python 的輕鬆閲讀

寫寫 Python,還有關於 Python 延伸的項目

Python + Line Bot SDK — 爬蟲以及推送訊息

說明

這裏用 BeautifulSoup 來爬一個網站

將取得的金額,儲存起來,當作下一次比對的條件

只要遇到金額有所不同,就用 LINE 發出訊息出來

準備東西

要準備的東西:

  • BeautifulSoup4requestsline-bot-sdkpymysql

還有 heroku 服務就可以了

安裝套件

pip install BeautifulSoup4
pip install pymysql
pip install line-bot-sdk

開發開始

import requests
import pymysql.cursors
import logging
from bs4 import BeautifulSoup

from linebot import LineBotApi
from linebot.models import TextSendMessage

因為這只有傳送文字,所以只用到 linebot 裏面的 TextSendMessage

直接將 LineBotApi 加上 Acesss Token 就可以讓它為你工作

line_bot_api = LineBotApi([LINE 的開發 Access Token])

資料庫

這裏直接用 pymysql 連接資料庫 給他一個 connectDB 連結,後面會用到

def connectDb(dbName):
    try:
        mysqldb = pymysql.connect(
                host="HOST",
                user="USER",
                passwd="PASSWORD",
                database=dbName,
                charset='utf8mb4'
        )
        return mysqldb
    except Exception as e:
        logging.error('Fail to connection mysql {}'.format(str(e)))
    return None

開始爬蟲,針對網站的分析

第一階段,屬於左邊的項目,主要有 div,class 對於 column-yellow,總共有 8 個 div

然後有屬於 font 的 class 是 biger 才是真正的價錢


所以寫出以下的 code

user_id = "[LINE User ID]"

def cralwer():
    response = requests.get("https://www.gck99.com.tw")
    soup = BeautifulSoup(response.text, "html.parser")
    rows = soup.findAll('div', {'class': 'column-yellow'})
    
    db_index = 0
    price_gold_text = ['黃金條塊', '飾金回收不扣耗損回收價', '白金回收即時價格', '999白銀加價回收', '22k', '18k', '14k', '10k']
    # 依序:黃金條塊、飾金回收不扣耗損回收價、白金回收即時價格、999白銀加價回收
    for row in rows:
        if row.find('font', {'class': 'biger'}) is not None:
            db_index += 1
            update = 0
            price = row.find('font', {'class': 'biger'}).text
            # print(db_index, price)

            # 資料庫的 price
            conn = connectDb('資料庫')
            cursor = conn.cursor()
            sql = f"SELECT * FROM `prices` where id = {db_index}"
            cursor.execute(sql)
            result = cursor.fetchone()
            print(result[1], price)
            if int(result[1]) != int(price):
                update = 1
                msg = "\n" +price_gold_text[db_index-1] + ':' + str(result[1]) + ' => ' + str(price)
                lineNotifyMessage(user_id, msg)
            conn.close()

            if update == 1:
                conn = connectDb('資料庫')
                cursor = conn.cursor()
                sql = f"UPDATE `prices` SET `price` = {price} where id = {db_index}"
                print(sql)
                cursor.execute(sql)
                conn.commit()
                conn.close()

第二階段,屬於左邊的項目,主要有 div,class 對於 column-blue,總共有 8 個 div

然後有屬於 font 的 class 是 biger 才是真正的價錢


    rows = soup.findAll('div', {'class': 'column-blue'})

    # 依序:22k、18k、14k、10k
    for row in rows:
        if row.find('font', {'class': 'biger'}) is not None:
            db_index += 1
            update = 0
            # print(db_index, row.find('font', {'class': 'biger'}).text)
            price = row.find('font', {'class': 'biger'}).text
            # 資料庫的 price
            conn = connectDb('資料庫')
            cursor = conn.cursor()
            sql = f"SELECT * FROM `prices` where id = {db_index}"
            cursor.execute(sql)
            result = cursor.fetchone()
            print(result[1], price)
            if int(result[1]) != int(price):
                update = 1
                msg = "\n" + price_gold_text[db_index-1] + ':' + str(result[1]) + ' => ' + str(price)
                print(msg)
                lineNotifyMessage(user_id, msg)
            conn.close()

        if update == 1:
            conn = connectDb('資料庫')
            cursor = conn.cursor()
            sql = f"UPDATE `prices` SET `price` = {price} where id = {db_index}"
            cursor.execute(sql)
            conn.commit()
            conn.close()

上面針對網頁,爬取金額,而且會給資料庫比對 如果資料庫的金額跟網頁爬取的價錢不符,就發送訊息給 LINE Bot 就結束

LINE Bot 發送訊息

這裏發送訊息的功能

def lineNotifyMessage(user_id, msg):
    line_bot_api.push_message(user_id, TextSendMessage(text=msg))

已經完成了 LINE Bot 給完成了

加入 keroku 的 scheduler

進入 Resources 加入 Heroku Scheduler 改成每 10 分鐘跑一次

python manage.py


CC BY-NC-ND 2.0 版权声明

喜欢我的文章吗?
别忘了给点支持与赞赏,让我知道创作的路上有你陪伴。

第一个支持了这篇作品
加载中…
加载中…

发布评论