python3 下载特定网页上的文件

本文介绍如何使用Python的urllib库从特定网页上抓取并下载文件到本地指定目录。通过正则表达式解析HTML源码,提取出目标文件的URL,并实现文件的下载。提供了两种下载方法:urllib.request.urlretrieve()和自定义读写循环。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

python3 下载特定网页上的文件

参考:https://blog.csdn.net/csdn86868686888/article/details/82108146
https://www.cnblogs.com/rkfeng/p/8366327.html
源码如下

# -*- coding: utf-8 -*-
import urllib3,urllib,time,re,sys,ssl,os
from urllib import request
import urllib.request
import subprocess
"""
Created on Wed Mar 13 10:35:48 2019

@author: fern.xu
"""

#对目标网站进行html源码查看
ssl._create_default_https_context = ssl._create_unverified_context
url = "http://xxx.xxx.xxx.xxx:8081/nexus/content/repositories/releases/wolaidai/welab-kms/27345/"
page = request.urlopen(url)
html = page.read().decode('utf-8') 

#使用正则对源码html中匹配.jar的绝对url地址
reg = r'<a href="(.+?\.jar)">' 
imgre = re.compile(reg) 
imglist = re.findall(imgre,html) 

#print (imglist[0])

#从url中提取文件名
url_filename = os.path.basename(imglist[0])
print(url_filename)

#组装在WINDOWS文件要保存路径与名称
winpath = r'D:\work\pywork'
#filename = r'agreement.jar'
#dest_dir = os.path.join(winpath,filename)
#print(dest_dir)

dest_dir = os.path.join(winpath,url_filename)
print(dest_dir)


#对文件进行下载
#方法1
#urllib.request.urlretrieve(imglist[0],dest_dir)
#方法2
response = request.urlopen(imglist[0])
chunk = 16*1024
with open(dest_dir,"wb") as f:
    while True:
        chunk = response.read(chunk)
        if not chunk:
            break
        f.write(chunk)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

徐为波

看着给就好了,学习写作有点累!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值