封装_requests爬虫爬取天气网景区天气.py
#爬取天气网景区天气
import requests
import re#正则表达式提取数据
def get_webtext():
web='http://www.weather.com.cn/weather1d/101290101.shtml'#爬取网页
web_open=requests.get(web)#打开浏览器并打开网站
web_open.encoding='utf-8'#设置编码格式 中文
return web_open.text
def get_usefull_information(str):
"""
<span class="name">大理</span>
<span class="weather">小雨</span>
<span class="wd">18/27℃</span>
<span class="zs">适宜</span>
"""
city=re.findall('<span class="name">([\u4e00-\u9fa5]*)</span>',str)#[\u4e00-\u9fa5]* 匹配中文字符字符0次或多次 分组() 改变限定符作用 ()只提取()n内的内容
weather=re.findall('<span class="weather">([\u4e00-\u9fa5]*)</span>',str)
temperature=re.findall('<span class="wd">(.*)</span>',str)
condition=re.findall('<span class="zs">([\u4e00-\u9fa5]*)</span>',str)
scenicarea_list=list(zip(city,weather,temperature,condition))
return scenicarea_list
openpyxl处理Excel.py
"""
openpyxl
load_workbook(filename) 打开已存在的表格,结果为工作簿对象
workbook.sheetnames 工作簿对象属性的sheetnames属性,用于获取所有工资表的名称,结果为列表
sheet.append(list) 向工资表中添加一行数据,新数据接在工资表已有数据的后面
workbook.save(excelname) 保存工作簿
Workbook() 创建新的工作簿对象
"""
#处理爬虫爬取的景区天气
import 封装_requests爬虫爬取天气网景区天气
import openpyxl
str=封装_requests爬虫爬取天气网景区天气.get_webtext()
weather_list=封装_requests爬虫爬取天气网景区天气.get_usefull_information(str)
excelbook=openpyxl.Workbook()#创建工作簿对象
excelbook_sheet=excelbook.create_sheet("景区天气")#工作博中创建工作表,命名为景区天气
for item in weather_list:
excelbook_sheet.append(item)
excelbook.save("景区天气.xlsx")#使用excel打开
openpyxl读取excel数据.py
import openpyxl
workbook_open=openpyxl.load_workbook("景区天气.xlsx")#打开工作簿
workbook_sheet=workbook_open["景区天气"]#选择操作的工作表
weather_list=[]
for row in workbook_sheet.rows:#sheet.rows获取工作表行数据
cell=[]#存贮单元格数据
for item in row:
cell.append(item.value)#打点调用属性 cell.value属性来获取单元格的真实值
weather_list.append(cell)
for item in weather_list:
print(item)
运行结果
openpyxl处理Excel.py
注意保存路径
openpyxl读取excel数据.py