- 導入依賴庫,沒有安裝的需要安裝
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import requests
from bs4 import BeautifulSoup
import xlsxwriter
- 由於抓取的7天的天氣預報數據所以清空ABC三列的前7行
# 創建excel
workbook = xlsxwriter.Workbook("weather.xlsx")
# 創建sheet
worksheet = workbook.add_worksheet("weather")
# 清空列以及行數
worksheet.set_column("A:A", 7)
worksheet.set_column("B:B", 7)
worksheet.set_column("C:C", 7)
- 數據存儲方法,看到下面的返回的數據就可以知道為什么傳入參數是list
# 存儲數據 方法
def savedata(colom, content_list):
# 傳入參數 colom: 操作的行 content_list:行中每列內容
colom_a = "A" + colom
colom_b = "B" + colom
colom_c = "C" + colom
# 日期
worksheet.write(colom_a, content_list[0])
# 天氣
worksheet.write(colom_b, content_list[1])
# 最高溫度 - 最低溫度
worksheet.write(colom_c, content_list[2] + "-" + content_list[3])
- 獲取html方法
def get_content(url, data=None):
rep = requests.get(url, timeout=60)
rep.encoding = 'utf-8'
return rep.text
- 獲取數據用到了BeautifulSoup
# 獲取數據
def get_data(htmltext, city):
content = []
bs = BeautifulSoup(htmltext, "html.parser")
body = bs.body
data = body.find('div', {'id': '7d'})
ul = data.find('ul')
li = ul.find_all('li')
for day in li:
# line = [city] # 城市名
line = []
date = day.find('h1').string
line.append(date) # 日期
text = day.find_all('p')
# 天氣狀況
line.append(text[0].string)
# 最高溫度
if text[1].find('span') is None:
temperature_H = None
else:
temperature_H = text[1].find('span').string.replace('℃', '')
# 最低溫度
temperature_L = text[1].find('i').string.replace('℃', '')
line.append(temperature_H)
line.append(temperature_L)
content.append(line)
# 返回的一個list,list里面每個元素又是一個list,其中包含4個元素 天氣狀況, 日期, 最高,最低溫度
return content
- 根據城市名稱獲城市代碼 拼接完整url
# 根據城市名稱拼接url
def get_url(city_name):
url = 'http://www.weather.com.cn/weather/'
with open('city.txt', 'r', encoding='UTF-8') as fs:
lines = fs.readlines()
for line in lines:
if(city_name in line):
code = line.split('=')[0].strip()
return url + code + '.shtml'
raise ValueError('invalid city name')
- 抓取天氣打印,並存儲到 excel中
if __name__ == '__main__':
cities = input('請輸入城市名稱:').split(" ")
print("| 日期 | 天氣狀況 | 溫度 |")
print("-----------------------------------------")
for city in cities:
url = get_url(city)
html = get_content(url)
result = get_data(html, city)
# 從第二行開始存儲,因為第一行 ["日期", "天氣狀況", "溫度", ""] 存儲這些信息
colom = 2
savedata("1", ["日期", "天氣狀況", "溫度", ""])
for day_list in result:
# 存儲數據
savedata(("%d" % (colom)), day_list)
# 一共7天數據
colom = colom + 1
if len(day_list[1]) == 1:
day_list[1] = " " + day_list[1] + " "
elif len(day_list[1]) == 2:
day_list[1] = " " + day_list[1] + " "
elif len(day_list[1]) == 4:
day_list[1] = " " + day_list[1] + " "
elif len(day_list[1]) == 3:
day_list[1] = " " + day_list[1] + " "
if len(day_list[0]) == 6:
day_list[0] = day_list[0] + " "
if len(day_list[3]) == 1:
day_list[3] = day_list[3] + " "
print("| " + day_list[0] + " | " + day_list[1] + " | " + day_list[2] + "℃ ~ " + day_list[3] + "℃ |")
print("-----------------------------------------")
# 操作完畢關閉excel 類似數據庫操作
workbook.close()
-
運行完畢打印結果:
-
生成的excel文件在同級目錄下:
-
城市對應的城市代碼是本地文件.鏈接:https://pan.baidu.com/s/1i5j00sP