python学习 openpyxl模块 excel交互使用

封装_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

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值