使用Python自動抓取CrossFit訓練課表

http://wod-gen.com/作為抓取對象

#匯入模組
import requests
import random
from bs4 import BeautifulSoup
#使用random選擇頁數,該網站有效頁面共636頁
page = random.randint(1,636)
#轉換成str型態,才能跟底下網址配在一起,以達成隨機開啟頁面
page = str(page)
print('The Page is:',page+'\n') #第幾頁
resp = requests.get('http://wod-gen.com/exercise/'+page) #隨機開一頁soup = BeautifulSoup(resp.text, 'html.parser')
name=soup.find_all('h2')[0].get_text() #課表名稱
print(name)
try:
time=soup.find_all('h2')[1].get_text() #訓練時間
print(time)
except:
pass
workout=soup.find_all('ul')[0].get_text() #訓練內容
print(workout)
try:
description=soup.find_all('h3')[0].get_text() #訓練描述
print(description)
except:
pass
with open('TodaysWorkout.txt','w') as f: #寫入至txt檔
try:
f.write(name+'\n')
f.write(time+'\n')
f.write(workout+'\n')
f.write(description+'\n')
except:
pass

心得:

使用random模組產生數字,將數字轉成str,與網址做連結搭配

2.try/except的使用:

遇到錯誤時沒關係,使用except就可以把它們pass過去

Written by

Machine Learning / Deep Learning / Python / Flutter cakeresume.com/yanwei-liu

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store