〇、前情提要
学习小甲鱼的使用Python读写Excel文件。这是上篇。
参考:
- 【办公篇】《极客Python之效率革命》(小甲鱼)https://www.bilibili.com/video/av23697305/?p=1
------------第一课------------
- [办公] 使用Python读写Excel文件(1)
https://fishc.com.cn/thread-101887-1-1.html - [模块档案] openpyxl 模块中文文档(一个读写 EXCEL 文件的模块)https://blog.csdn.net/weixin_43210113/article/details/107505405
- 爬取豆瓣 TOP250 电影排行榜
https://fishc.com.cn/thread-94979-1-1.html - 豆瓣电影 Top 250
https://movie.douban.com/top250 - 我的笔记-【爬虫篇】《极客Python之效率革命》(小甲鱼) b站笔记
https://blog.csdn.net/weixin_43210113/article/details/107505405
------------第二课------------
- [办公] 使用Python读写Excel文件(2)
https://fishc.com.cn/thread-102046-1-1.html
------------第三课------------
- [办公] 使用Python读写Excel文件(3)
https://fishc.com.cn/thread-102708-1-1.html
------------第四课------------
- [办公] 使用Python读写Excel文件(4)
https://fishc.com.cn/thread-103472-1-1.html
------------第五课------------
- [办公] 使用Python读写Excel文件(5)
https://fishc.com.cn/thread-103980-1-1.html
------------第六课------------
- [办公] 使用Python读写Excel文件(6)
https://fishc.com.cn/forum.php?mod=viewthread&tid=141918&extra=page%3D1%26filter%3Dtypeid%26typeid%3D722
我的笔记:
- 【Python】办公篇-《极客Python之效率革命》(小甲鱼) 笔记一
https://blog.csdn.net/weixin_43210113/article/details/107548337 - 【Python】办公篇-《极客Python之效率革命》(小甲鱼) 笔记二
https://blog.csdn.net/weixin_43210113/article/details/107564712
提示:
- wb为workbook,
wb["sheetname"]
表示选中一张worksheet - ws为worksheet,
ws['A1']
表示选中一个单元格 - 由于视频录制年份较早,现在的语句都会有
DeprecationWarning: Call to deprecated function 过时的语句 (Use 推荐的语句).
提示,可根据自身需求来使用 - 由于权限问题,请关闭excel表后再save
- 有些内容不如在excel表中直接修改,但量大时使用python会很有效
一、P1 使用Python读写Excel文件(1)
openpyxl 模块
[模块档案] openpyxl 模块中文文档(一个读写 EXCEL 文件的模块)
https://fishc.com.cn/thread-101547-1-1.html
安装openpyxl pip3 install openpyxl
测试import openpyxl
创建并保存 Excel 文件
import openpyxl
import datetime
wb = openpyxl.Workbook()
# 获取活跃的工作表
ws = wb.active
# 数据可以直接赋值给单元格
ws['A1'] = 520
# 可以整行添加
ws.append([1, 2, 3])
# Python 类型将自动转换
ws['A3'] = datetime.datetime.now()
# 保存文件
wb.save("demo.xlsx")
将豆瓣 TOP250 电影排行榜保存为 Excel 文件
爬取豆瓣 TOP250 电影排行榜
https://fishc.com.cn/thread-94979-1-1.html
豆瓣电影 Top 250
https://movie.douban.com/top250
我的笔记-【爬虫篇】《极客Python之效率革命》(小甲鱼) b站笔记
https://blog.csdn.net/weixin_43210113/article/details/107505405
import requests
import bs4
import re
import openpyxl
def open_url(url):
# 使用代理
# proxies = {"http": "127.0.0.1:1080", "https": "127.0.0.1:1080"}
headers = {
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.98 Safari/537.36'}
# res = requests.get(url, headers=headers, proxies=proxies)
res = requests.get(url, headers=headers)
return res
def find_movies(res):
soup = bs4.BeautifulSoup(res.text, 'html.parser')
# 电影名
movies = []
targets = soup.find_all("div", class_="hd")
for each in targets:
movies.append(each.a.span.text)
# 评分
ranks = []
targets = soup.find_all("span", class_="rating_num")
for each in targets:
ranks.append