建築商情資料(建造執照)Python爬蟲並透過SMTP以Outlook寄信通知 並部署到Azure VM做排程

source:

Msx Wu
WU TH Max
Published in
8 min readApr 8, 2021

--

包含全縣市三個月份資料
點擊資料下載後頁面

Code:

url = "https://cpabm.cpami.gov.tw/e_help.jsp"r = requests.get(url)soup = bs(r.text, 'html.parser')a = soup.find_all('a')links = []for A in a:if('資料下載' in A):links.append(A.get('href'))

首先先直接request url得到html raw data
接著beautiful soup撈出所有資料下載的 a tag
並取出所有a tag中href attr存在一個list中

for link in links:logging.info('requesting: {}/{}'.format(i,len(links)))t = pd.read_html(link, header=0)df = df.append(t[0], ignore_index=True)

對剛剛存了所有url的list開始個別request
因為網頁資料下載這頁面中本身就是個html table
所以可以直接用pandas中read_html這個方法來讀
再將所有結果append到同一個dataframe中

df['總樓層數'] = df['地下層數']+df['地上層數']df = df[(df['總樓層數']>2)&(df['變更次數']<4)]df = df.sort_values(['總樓層數'], ascending=(False))
try:
df1.to_excel("df.xlsx", index=False)except Exception as e:logging.error(e)sys.exit(e)

處理dataframe資料 新增一個column用來判斷用
接著篩掉總樓層>2, 變更次數<4的欄位
最後用總樓層做降冪排列 匯出成xlsx檔

writer = pd.ExcelWriter('df.xlsx', engine = 'xlsxwriter')df1.to_excel(writer, sheet_name='Sheet1')# Get the xlsxwriter objects from the dataframe writer object.workbook  = writer.bookworksheet = writer.sheets['Sheet1']# Apply the autofilter based on the dimensions of the dataframe.worksheet.autofilter(0, 0, df.shape[0], df.shape[1])writer.save()

這邊用xlsxwriter加了個header的autofilter進去
到這邊excel處理端完成

Result Preview:

輸出為xlsx (filter: 總樓層數降冪排列, 變更次數<4, 總樓層數>2)

發信作業:

實際收信狀況預覽

使用上用Microsoft Outlook 365做發信機構
實際上不太建議用Outlook 因為直接輸入password
Gmail能額外開一個Application Key做使用較符合狀況

content = MIMEMultipart()  #建立MIMEMultipart物件content["subject"] = "建築商情資料整理"  #郵件標題content["from"] = "@outlook.com"  #寄件者content["to"] = "@gmail.com" #收件者try:xlsx = MIMEApplication(open("df.xlsx", 'rb').read())except Exception as e:logging.error(e)sys.exit(e)xlsx.add_header('Content-Disposition', 'attachment', filename= "建照.xlsx")content.attach(xlsx)

建立MIMEMultipart物件 將信件資訊輸入完成
接著用MIMEApplication去讀我們剛剛存的xlsx
將xlsx當作一個attach加入的信件中

with smtplib.SMTP(host="smtp.office365.com", port="587") as smtp:  # 設定SMTP伺服器try:smtp.ehlo()  # 驗證SMTP伺服器smtp.starttls()  # 建立加密傳輸smtp.login(email, password)  # 登入寄件者smtp.send_message(content)  # 寄送郵件logging.info('Mail Sending Completed.')except Exception as e:logging.error(e)

這邊設定參考outlook相關參數設定

寄信端結束

部署到Azure VM做排程

環境:Linux (debian 10.9)
發行者: bitnami
供應項目:wordpress
(原本這VM是用來架設其他wordpress)

sudo scp -i _.pem -r /Users/zhihuiwu/Documents/buildingLicense _____@___.__.___.___:~/.

先將local端的資料夾移入vm
注意的是 scp進Azure VM只能進default path(~:/.)
如果設其他路徑會被denied掉
然後記得移入前 不要把python那些package一起移進去
因為這樣要花費非常長的時間
建議先freeze 到 requirements.txt
進去vm環境再install

ssh -i _.pem _____@___.__.___.___

透過ssh進入vm

ssh進入
確認資料有進來
sudo apt install python3 python3-venv
sudo apt install python3-pip
python3 -m venv venv

預設好python環境

. venv/bin/activate
pip3 install -r requirements.txt
確認requirements modules都進來

以上環境建立完成 也確定能直接run python

接著利用crontab來做排程

crontab -e

進入crontab編輯模式

00 09 16 */3 * /home/JTPKB/buildingLicense/venv/bin/python3 /home/JTPKB/buildingLicense/main.py

設定每三個月的16號早上九點 透過我們建立的venv跑指定的py file

確認crontab -l

--

--