iT邦幫忙

2021 iThome 鐵人賽

DAY 17
0
AI & Data

網路爬蟲,萬物皆爬 - 30 天搞懂並實戰網路爬蟲及應對反爬蟲技術系列 第 17

【Day 17】- 手動更新匯率太麻煩了! 匯率爬蟲搭配 OpenPyXL 做到自動讀取&更新匯率!

前情提要

前一篇介紹了 openpyxl 這項可以操作 excel 的工具。

開始之前

本篇實戰 【Day 15】- 匯率什麼的。爬! (實戰匯率爬蟲 on chrome) 所撰寫的匯率爬蟲 使用openpyxl 將匯率更新在 excel。

預期結果

可以簡單地將想要爬取的匯率寫在 excel ,執行程式後自動將爬取到的匯率更新在 excel 上。

實作

首先,先從 excel 下手,先將目標 excel 讀入,並讀取目前 row 的最大值。

import openpyxl

workbook = openpyxl.load_workbook('匯率及時更新.xlsx')
sheet = workbook['及時匯率']
mxR = sheet.max_row
print(mxR)
#Output : 4

接下來,讀取 row = 2~mxR, column = 1 的單元格,並將其加入一串列。

import openpyxl

workbook = openpyxl.load_workbook('匯率及時更新.xlsx')
sheet = workbook['及時匯率']
mxR = sheet.max_row
cointypes = []
for r in range(2, mxR+1):
    cointype = sheet.cell(row=r, column=1).value
    cointypes.append(cointype)

print(cointypes)
#Output: ['美金', '日幣', '歐元']

讀取表單部分完工後,我們將匯率爬蟲與此結合,並將匯率爬蟲包為一個函式,以幣種作為輸入、匯率作為回傳值。

import openpyxl
import requests
from bs4 import BeautifulSoup

def crawler(cointype):
    url = f'https://www.google.com/search?q={cointype}'
    user_agent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.61 Safari/537.36'
    resp = requests.get(url, headers={
        'user-agent': user_agent
    })
    soup = BeautifulSoup(resp.text, 'html5lib')
    ele = soup.find('span', class_='DFlfde SwHCTb')

    if ele:
        return ele.text
    else:
        return None

workbook = openpyxl.load_workbook('匯率及時更新.xlsx')
sheet = workbook['及時匯率']
mxR = sheet.max_row
cointypes = []
for r in range(2, mxR+1):
    cointype = sheet.cell(row=r, column=1).value
    cointypes.append(cointype)

接下來,我們簡單寫個 for-loop 將 cointypes 內的每個元素都呼叫一次匯率爬蟲,並將結果用 openpyxl 存於 excel,最後儲存 excel 即可。

記得執行該程式的過程,需先將目標 excel 檔案先關閉,否則會出現錯誤。

import openpyxl
import requests
from bs4 import BeautifulSoup

def crawler(cointype):
    url = f'https://www.google.com/search?q={cointype}'
    user_agent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.61 Safari/537.36'
    resp = requests.get(url, headers={
        'user-agent': user_agent
    })
    soup = BeautifulSoup(resp.text, 'html5lib')
    ele = soup.find('span', class_='DFlfde SwHCTb')

    if ele:
        return ele.text
    else:
        return None

workbook = openpyxl.load_workbook('匯率及時更新.xlsx')
sheet = workbook['及時匯率']
mxR = sheet.max_row
cointypes = []
for r in range(2, mxR+1):
    cointype = sheet.cell(row=r, column=1).value
    cointypes.append(cointype)

nowrow = 2
for cointype in cointypes:
    result = crawler(cointype)
    sheet.cell(row=nowrow, column=2).value = result
    nowrow += 1

workbook.save('匯率及時更新.xlsx')

結語

今天帶各位實作用 openpyxl 套件,將匯率爬蟲爬取回來的資料更新到 excel 上,這個操作 excel 的方法也可用於很多地方,像是學校消警告時老師指派的工作(X。

明日內容

明天會跟各位介紹 selenium 這個套件,這個套件對於爬取動態網頁設計的網站十分方便。

補充資料

openpyxl Docs : https://openpyxl.readthedocs.io/en/stable/

[2020鐵人賽Day16]糊裡糊塗Python就上手-Python Excel 操縱套餐(使用openpyxl) : https://ithelp.ithome.com.tw/articles/10246377

OpenPyXL的使用教程(一) : https://www.jianshu.com/p/642456aa93e2


上一篇
【Day 16】- 做 Excel 輸入數據到心累?消警告的服學輸入很繁瑣? 使用 openpyxl 來操作 Excel
下一篇
【Day 18】- 像個使用者的爬蟲 Selenium
系列文
網路爬蟲,萬物皆爬 - 30 天搞懂並實戰網路爬蟲及應對反爬蟲技術30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言