python第五次作业

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

  • 匹配陕西省区号 029-12345

  • 匹配邮政编码 745100

  • 匹配邮箱 lijian@xianoupeng.com

  • 匹配身份证号 62282519960504337X

python 复制代码
import re

# 1. 匹配陕西省区号 029-12345
area_code_pattern = r'^029-\d+$'
area_code = "029-12345"
print("陕西省区号匹配结果:", re.match(area_code_pattern, area_code) is not None)  # True

# 2. 匹配邮政编码 745100
postcode_pattern = r'^\d{6}$'
postcode = "745100"
print("邮政编码匹配结果:", re.match(postcode_pattern, postcode) is not None)  # True

# 3. 匹配邮箱 gxy230718@163.com
email_pattern = r'^[a-zA-Z0-9_]+@[a-zA-Z0-9.]+\.[a-zA-Z]{2,4}$'
email = "lijian@xianoupeng.com"
print("邮箱匹配结果:", re.match(email_pattern, email) is not None)  # True

# 4. 匹配身份证号 500227200409173925
id_card_pattern = r'^\d{17}[\dX]$'
id_card = "500227200409173925"
print("身份证号匹配结果:", re.match(id_card_pattern, id_card) is not None)  # True

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

python 复制代码
import requests
from bs4 import BeautifulSoup


# 定义装饰器:记录爬取日志+异常处理
def spider_decorator(func):
    def wrapper(url):
        print(f"开始爬取网址:{url}")
        try:
            # 执行原爬虫函数
            result = func(url)
            print("爬取完成,图片路径已保存到本地")
            return result
        except Exception as e:
            print(f"爬取失败,错误信息:{e}")
            return []

    return wrapper


# 被装饰的爬虫函数:爬取图片路径并保存
@spider_decorator
def get_school_images(url):
    # 请求头:模拟浏览器访问,避免被反爬
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"
    }
    # 发送请求获取网页内容
    response = requests.get(url, headers=headers, timeout=10)
    response.encoding = response.apparent_encoding
    soup = BeautifulSoup(response.text, "html.parser")
    # 提取所有img标签的src属性
    img_paths = [img.get("src") for img in soup.find_all("img") if img.get("src")]

    # 去重
    img_paths = list(set(img_paths))

    # 将路径保存到本地文件
    with open("image_paths.txt", "w", encoding="utf-8") as f:
        for path in img_paths:
            f.write(path + "\n")

    return img_paths

if __name__ == "__main__":
    school_url = "https://www.nhjc.com"
    get_school_images(school_url)
相关推荐
ycjunhua几秒前
终极入门:uv —— 超快 Python 包 / 环境管理工具(Windows 完整版)
windows·python·uv
2401_883600251 分钟前
SQL视图名称冲突如何避免_建立规范化的命名空间与管理
jvm·数据库·python
JAVA学习通2 分钟前
AI Agent 工具调用机制深度解析与 Spring Boot 工程集成实战(2026版)
java·人工智能·spring boot·python·spring
亿牛云爬虫专家3 分钟前
解决 Python 爬虫代理 407 错误:基于 urllib3 更新与爬虫代理的实战指南-2
爬虫·python·爬虫代理·authentication·urllib3·407·base64 编码
m0_640309304 分钟前
CSS中如何让浮动元素撑开父容器_深度解析清除浮动
jvm·数据库·python
2301_816660214 分钟前
Golang bufio怎么读取用户输入_Golang标准输入读取教程【详解】
jvm·数据库·python
Foreer黑爷5 分钟前
Java多线程编程:Thread与Runnable的并发控制
java·开发语言
南宫萧幕5 分钟前
从YALMIP工具箱到车辆工况仿真:MATLAB控制策略开发的完整实践指南
开发语言·人工智能·matlab·simulink
WJ.Polar6 分钟前
Ansible任务控制
linux·运维·网络·python·ansible
泰迪智能科技016 分钟前
图书教材推荐|Python网络爬虫技术(第2版)(微课版)
开发语言·爬虫·python