使用Python去爬取中國天氣網的近7天天氣情況
阿新 • • 發佈:2019-01-27
import requests from bs4 import BeautifulSoup address = 'http://www.weather.com.cn/weather/101{}.shtml' for i in range(1,24): z = '' if i<5: z = '0'+str(i)+'0100' if i>4 and i<10: z = '0'+str(i)+'0101' if i>9: z = str(i)+'0101' address1 =address.format(z) #print(address1) w = requests.get(''+address1+'') #轉換編碼解決中文問題 t1 = w.text.encode('ISO-8859-1').decode('utf-8') ht1 = BeautifulSoup(t1,'html5lib') body1 = ht1.body # 獲取body部分 # print(body1) data = body1.find('div', {'id': '7d'}) # 找到id為7d的div ul = data.find('ul') # 獲取ul部分 li = ul.find_all('li') # 獲取所有的li s = body1.find('div',{'class':'crumbs'}) #找到class為crumbs的div a = s.find_all('a') # 獲取a標籤 #print(s) if len(a) == 1: print(a[0].text) else: print(a[0].text,'-',a[1].text,end='\n') #print(li) list = [] for day in li: # 對每個li標籤中的內容進行遍歷 # temp代存每日的資料 temp = [] # 新增日期 data = day.find('h1').string # 找到日期 temp.append(data) # 新增到temp中 inf = day.find_all('p') # 找到li中的所有p標籤 # 新增天氣狀況 temp.append(inf[0].string) # 第一個p標籤中的內容(天氣狀況)加到temp中 # 新增溫度 tem = day.find('i').string # 找到溫度 temp.append(tem) # 新增到temp中 inf = day.find_all('i') # 找到li中的所有p標籤 list.append(temp) # 將temp 加到list中 for j in range(len(list)): print(list[j],end='\n')
輸出結果: