使用python批量下载网上文件

import requests,re,os

r=requests.get('https://github.com/roy-tian/learning-area/blob/master/html/tables/assessment-start/images/')

urls=re.findall(r'MiracleYoung/You-are-Pythonista/blob/master/PythonExercise/App/plan_game/material_images/\w+.png',r.text)

for v,url in enumerate(urls): url='https://raw.githubusercontent.com/'+url.replace('/blob','')

path = 'D://pict/' + url.split('/')[-1]

r = requests.get(url)

with open(path, 'wb')as f:

f.write(r.content)

f.close()

代码解释

这段代码使用了Python编程语言,并涉及到几个Python库的使用:`requests`、`re` 和 `os`。下面我们详细分析这段代码的含义和相关概念。

代码分析

  1. 导入库

    import requests, re, os
    
    • requests:用于发送HTTP请求的库,方便进行网络请求操作。
    • re:正则表达式库,用于在字符串中查找特定模式。
    • os:提供与操作系统交互的功能。
  2. 发送HTTP请求

    r = requests.get('https://github.com/roy-tian/learning-area/blob/master/html/tables/assessment-start/images/')
    
    • 使用requests.get()方法向指定的URL发送GET请求,并将响应存储在变量r中。
  3. 正则表达式查找URL

    urls = re.findall(r'MiracleYoung/You-are-Pythonista/blob/master/PythonExercise/App/plan_game/material_images/\w+\.png', r.text)
    
    • re.findall()方法用于在r.text(响应的文本内容)中查找所有匹配正则表达式的字符串。
    • 正则表达式r'MiracleYoung/You-are-Pythonista/blob/master/PythonExercise/App/plan_game/material_images/\w+\.png'用于匹配特定格式的PNG图片URL。
  4. 下载图片并保存

    for v, url in enumerate(urls):
        url = 'https://raw.githubusercontent.com/' + url.replace('/blob', '')
        path = 'D://pict/' + url.split('/')[-1]
        r = requests.get(url)
        with open(path, 'wb') as f:
            f.write(r.content)
            f.close()
    
    • 遍历urls列表中的每个URL。
    • 将URL转换为原始内容URL(raw.githubusercontent.com),以便直接访问文件。
    • 构造本地文件路径,将图片保存到D://pict/目录下。
    • 发送GET请求获取图片内容,并以二进制写入方式保存到本地文件。

相关概念

  • HTTP请求requests库简化了HTTP请求的发送和响应处理。GET请求用于从服务器获取数据。
  • 正则表达式re库提供了强大的字符串模式匹配功能,常用于文本解析和数据提取。
  • 文件操作:使用open()函数以二进制写入模式('wb')打开文件,确保图片数据正确保存。

示例代码

以下是一个简单的示例,展示如何使用requests库下载文件:

import requests

url = 'https://example.com/image.png'
response = requests.get(url)

with open('image.png', 'wb') as file:
    file.write(response.content)

文档链接

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值