爬蟲筆記-(利用openpyxl紀錄爬取的匯率資料)
嘗試將爬取到的匯率資料存入EXCEL中


觀察上面頁面可以了解我們需要的幣值資料位於網頁中
span標籤中帶有class=DFlfde SwHCTb
主要流程
建立工作表 > 建立欄位 > 根據欄位中的幣種代入爬蟲中,把抓到的幣值填入單元格
import requests
import html5lib
from bs4 import BeautifulSoup
import openpyxl
from datetime import datetime
def money_value(money):
url='https://www.google.com/search'
headers={'user-agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36'}
parmars={'q':money} #搜索的幣值
response=requests.get(url,headers=headers,params=parmars)
if response.status_code != 200:
return print(f'伺服器拒絕存取')
else:
soup=BeautifulSoup(response.text,'html5lib')
val=soup.find('span',class_='DFlfde SwHCTb')
if val:
return val.text
else:
return print(f'這個幣值的標籤在不同位置')
#檢查紀錄匯率資料的EXCEL是否存在,存在載入,否則建立
#製作workbook類的實例物件
#確認excel是否存在 ,存在就更新,不存在就建立
if os.path.exists('每日爬蟲匯率.xlsx'):
workbook=openpyxl.load_workbook('每日爬蟲匯率.xlsx')
else:
workbook=openpyxl.Workbook()
#製作一個工作表
now=datetime.now()
sheetname=now.strftime('%m-%d %H時 匯率')
#紀錄每次爬取匯率資料時間,間隔1時以上就使用不同頁面紀錄
sheet=workbook.create_sheet(title=sheetname,index=0)
#製作工作表時間,當工作表的名稱不重複的情況下,舊的工作表將會往後遞移一位
sheet.append(['幣種','匯率']) #標題
sheet['A2']='令吉'
sheet['A3']='美金'
sheet['A4']='歐元'
sheet['A5']='日幣'
sheet['A6']='人民幣'
print(f"確認一下目前工作表名稱={sheet.title}")
print(f"工作表的資料維度={sheet.dimensions}")
#要把匯率資料迭到B2:B6
for i,j in zip(sheet['A2':'A6'],sheet['B2':'B6']):
#i是單元格A2:A6的tuple
#(<Cell '05-27 16時 匯率'.A2>,)
#j是單元格B2:B6的tuple
#(<Cell '05-27 16時 匯率'.B2>,)
cash=money_value(i[0].value) #將爬取的匯率存到cash物件
j[0].value=cash #將幣值依序填入到B2到B6的單元格中
workbook.save('每日爬蟲匯率.xlsx') #存到這個EXCEL
------------------------------------
(?祈0_30) PS C:\Users\K\OneDrive\桌面\爬蟲0_30> & C:/Users/K/.virtualenvs/爬蟲0_30-yiVzn_yZ/Scripts/python.exe c:/U率.xlsx'sers/K/OneDrive/桌面/爬蟲0_30/匯率爬蟲.py s/K/.virtualenvs/爬蟲0_30-yiVzn_yZ/Scripts/python.exe c:/Users/K/OneDrive/桌面/爬蟲0_30/匯率爬蟲.py
確認一下目前工作表名稱=05-27 16時 匯率1
工作表的資料維度=A1:B6
標籤: 爬蟲

0 個意見:
張貼留言
訂閱 張貼留言 [Atom]
<< 首頁