【Python体验】第五天:目录搜索、数据爬虫(评论区里写作业)

文章目录

目录搜索 os、shutil库

os 模块提供了非常丰富的方法用来处理文件和目录。

os.listdir(path):返回path指定的文件夹包含的文件或文件夹的名字的列表。

os.path 模块:获取文件的属性信息。

os.path.join(path1, path2\[, ...]):把目录和文件名合成一个路径

os.path.isdir(path) :判断路径是否为目录

os.path.isfile(path):判断路径是否为文件

shutil.move(file,target):移动文件

python 复制代码
# 深度优先搜索文件 (目录搜索)

import os # 导入os模块
import shutil # 实现移动文件的功能需要

# path代表待搜索的目录路径,result存储搜索到的文件路径列表
def dfs(path, result):
    child_files = os.listdir(path)
    for child in child_files:
        # 使用join拼接子目录或文件的路径
        child = os.path.join(path, child)
        # 将child保存到result
        result.append(child)
        if os.path.isdir(child):
            dfs(child, result)

files = []
dfs('.', files)

# 遍历files
for file in files:
    print("find %s" %file) #打印搜索到的路径
    if(os.path.isfile(file) and file.endswith('.xlsx')):
        # 移动当前目录下的excel文件到excel目录下
        shutil.move(file, '.\excel')

移动前:

移动后:

数据爬虫 request、re

网页数据爬虫实现了互联网网页自动化下载与自动化解析。通过爬虫,可以下载和分析网页。

python 复制代码
# 网络爬虫

# spider.py:网页下载、链接提取、数据存储
# 查看豆瓣网top250(25页,每页25条)的电影简介地址,换行存入到txt中

import requests
import re

url = "https://movie.douban.com/top250?start="
pageSize = 25
headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36"
}
# 正则匹配
briefUrl = "https://movie.douban.com/subject/[0-9]+/"
txt = open("douban.txt", "a", encoding="utf-8")

# 爬取10页
for page in range(0, 10):
    resp = requests.get(url + str(page * pageSize), headers=headers)
    resp.encoding = "utf-8"
    # print(resp.text)

    # 通过findall从网页中提取符合briefUrl正则规则的网址
    links = re.findall(briefUrl, resp.text)
    # 去重
    arr = set(links)
    # print(links)
    for l in arr:
        # print(l)
        txt.write(l + "\n")
txt.close()

作业:爬取案例的top250电影的关键信息(名称、类型、日期),并保存在表格中

相关推荐
TomEval1 分钟前
【测AI】第05篇:Python 爬虫进阶 —— 动态页面爬取与 Scrapy 框架
人工智能·爬虫·python·scrapy·自动化
only-lucky5 分钟前
QML深入学习七(MVC模块)
学习·mvc
huisheng_qaq11 分钟前
【Python基础篇-07】深入理解python的面向对象编程
python·多态·继承·面向对象编程·封装
FanetheDivine11 分钟前
学习python 2.语法速览
python
奕鼎竜瑆19 分钟前
[新手小白也能学会] 01-PyTorch框架使用(上)
人工智能·pytorch·python
2401_8501220420 分钟前
高温耐油热缩套管选型:材料、温度和油液要匹配
经验分享·笔记·科技·学习
海天一色y25 分钟前
图像分割全解析:从经典算法到深度学习的原理与实战(Python + MATLAB)
python·深度学习·算法
三点水-here44 分钟前
从 Miniconda 迁移到 Miniforge3 全记录:安装、配置、环境迁移与排错实录
python·conda
Xudde.1 小时前
Me and My Girlfriend 靶机渗透测试(Vulnhub Writeup)
笔记·学习·安全·web安全
Canmag 兴隆磁性1 小时前
自动装盒设备 AO-WCMF
学习·永磁材料·充磁