openyxl模塊:用于處理excel文件的木塊,可以Excel中的數據進行寫入和讀取
函數或類的名稱 | 功能描述 |
load_workbook(filename) | 打開已經存在的工作簿,結果為工作簿對象 |
workbook.sheetnames | 工作簿對象的sheetnames屬性,用戶獲取所有工作表的名稱,結果為列表類型。 |
sheet.appenst) | 向工作表中添加一行數據,新數據接在工作表已有內容后面。 |
workbook.save(excelname) | 保存工作簿 |
weather.py
# coding:utf-8
import requests
import re
#發起請求
def get_html():url="http://www.weather.com.cn/weather1d/101010100.shtml"#反爬headers={'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36'}resp=requests.get(url, headers=headers)#resp相應結果對象#設置響應的編碼格式resp.encoding='utf-8'#print(resp.text)return resp.text
#獲取結果
def parse_html(html_str):city=re.findall('<span class="name">([\u4e00-\u9fa5]*)</span>',html_str)weather=re.findall('<span class="weather">([\u4e00-\u9fa5]*)</span>',html_str)wd=re.findall('<span class="wd">(.*)</span>',html_str)zs=re.findall('<span class="zs">([\u4e00-\u9fa5]*)</span>',html_str)lst = []for a, b, c, d in zip(city, weather, wd, zs):lst.append([a, b, c, d])return lst
獲取天氣預報網站.py
# coding:utf-8
import weather
import openpyxl
lst=weather.parse_html(weather.get_html())
#創建工作簿
workbook=openpyxl.Workbook()
#創建工作表對象
sheet=workbook.create_sheet('景區天氣')
#將數據添加到工作表
for item in lst:sheet.append(item)#一次添加一行
workbook.save('景區天氣.xlsx')
?