【Python练习五】Python 正则与网络爬虫实战:专项练习(2道经典练习带你巩固基础——看完包会)

第一题

题目:

使用正则完成下列内容的匹配

  • 匹配陕西省区号 029-12345
  • 匹配邮政编码 745100
  • 匹配邮箱 lijian@xianoupeng.com
  • 匹配身份证号 62282519960504337X

代码:

python 复制代码
import re
# 1. 匹配陕西省区号 029-12345
pattern_area = r'^029-\d{5}$'  # 精确匹配 029- 开头,后接5位数字
test_area = '029-12345'
print("区号匹配:", re.match(pattern_area, test_area) is not None)

# 2. 匹配邮政编码 745100
pattern_post = r'^\d{6}$'  # 精确匹配6位数字
test_post = '745100'
print("邮编匹配:", re.match(pattern_post, test_post) is not None)

# 3. 匹配邮箱 lijian@xianoupeng.com
pattern_email = r'^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$'
test_email = 'lijian@xianoupeng.com'
print("邮箱匹配:", re.match(pattern_email, test_email) is not None)

# 4. 匹配身份证号 62282519960504337X
pattern_id = r'^\d{17}[\dXx]$'  # 17位数字 + 1位数字或X/x
test_id = '62282519960504337X'
print("身份证匹配:", re.match(pattern_id, test_id) is not None)

运行结果:


第二题

题目:

爬取学校官网,获取所有图片途径并将路径存储在本地文件中,使用装饰器完成

代码:

python 复制代码
import requests
import re

# 装饰器:记录爬取任务
def log_crawl_task(func):
    def wrapper(url):
        print(f"开始爬取: {url}")
        result = func(url)
        print(f"爬取完成,共获取 {len(result)} 条图片路径")
        return result
    return wrapper

# 爬取函数
@log_crawl_task
def crawl_school_images(url):
    try:
        # 基础请求配置,避免被反爬
        headers = {"User-Agent": "Mozilla/5.0"}
        response = requests.get(url, headers=headers, timeout=10)
        response.encoding = "utf-8"  # 确保中文路径不乱码
        
        # 正则提取img标签的src属性
        img_paths = re.findall(r'<img src="(.*?)"', response.text)
        return img_paths
    except Exception as e:
        print(f"爬取失败: {str(e)}")
        return []

# 保存路径到本地文件
def save_image_paths(paths):
    with open("学校图片路径.txt", "w", encoding="utf-8") as f:
        f.write("\n".join(paths))
    print("图片路径已保存到 学校图片路径.txt")

# 调用示例
if __name__ == "__main__":
    school_url = "https://www.cqcst.edu.cn"
    image_paths = crawl_school_images(school_url)
    if image_paths:
        save_image_paths(image_paths)
    else:
        print("未获取到任何图片路径")

运行结果:


相关推荐
喵手1 小时前
Python爬虫实战:招聘会参会企业数据采集实战 - 分页抓取、去重与增量更新完整方案(附CSV导出 + SQLite持久化存储)!
爬虫·python·爬虫实战·增量·零基础python爬虫教学·招聘会参会企业数据采集·分页抓取去重
hoiii1871 小时前
基于C#实现的高性能实时MP4录屏方案
开发语言·c#
JasonSJX1 小时前
海海软件正式发布全新 DRM-X官网 Next.js 重构、多语言升级与 SEO 优化,助力全球数字版权保护
开发语言·javascript·安全·重构·视频防录屏·开源drm·加密保护课程
系统修复专家1 小时前
UG12.0官方未公开修复方法:彻底解决C++异常崩溃问题
开发语言·c++·安全·bug·dll·游戏报错
yongui478342 小时前
基于C#实现Modbus RTU通信
开发语言·c#
小鸡吃米…2 小时前
TensorFlow 实现循环神经网络
人工智能·python·tensorflow
阿钱真强道2 小时前
14 ThingsBoard实战:从零搭建设备配置+设备,完成MQTT温湿度上行/目标温度下行测试(对比JetLinks)
java·网络·python·网络协议
ssswywywht2 小时前
python练习
开发语言·python
PD我是你的真爱粉2 小时前
RabbitMQRPC与死信队列
后端·python·中间件