python多线程下载文件
从文件中读取图片url和名称,将url中的文件下载下来。文件中每一行包含一个url和文件名,用制表符隔开。
1、使用requests请求url并下载文件
def download(img_url, img_name):
with closing(requests.get(img_url, stream=True)) as r:
with open(os.path.join(out_dir, img_name), 'wb') as f:
for data in r.iter_content(1024):
f.write(data)
2、从文件中读取url,考虑文件较大,使用生成器的方式读取。
def get_imgurl_generate():
with open('./example.txt', 'r') as f:
for line in f:
line = line.strip()
yield imgs
3、使用多线程进行下载
lock = threading.Lock()
def loop(imgs):
while True:
try:
with lock:
img_url, img_name = next(imgs)
except StopIteration:
break
download_pic(img_url, img_name) img_gen = imgurl_generate() for i in range(0, thread_num):
t = threading.Thread(target=loop, args=(img_gen,))
t.start()
完整代码,加入异常处理
# -*- coding: utf-8 -*-
import os
from contextlib import closing
import threading
import requests
import time headers = {
'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36'
} #输出文件夹
out_dir = './output'
#线程数
thread_num = 20
#http请求超时设置
timeout = 5 if not os.path.exists(out_dir):
os.mkdir(out_dir) def download(img_url, img_name):
if os.path.isfile(os.path.join(out_dir, img_name)):
return
with closing(requests.get(img_url, stream=True, headers=headers, timeout=timeout)) as r:
rc = r.status_code
if 299 < rc or rc < 200:
print 'returnCode%s\t%s' % (rc, img_url)
return
content_length = int(r.headers.get('content-length', ''))
if content_length == 0:
print 'size0\t%s' % img_url
return
try:
with open(os.path.join(out_dir, img_name), 'wb') as f:
for data in r.iter_content(1024):
f.write(data)
except:
print 'savefail\t%s' % img_url def get_imgurl_generate():
with open('./final.scp', 'r') as f:
index = 0
for line in f:
index += 1
if index % 500 == 0:
print 'execute %s line at %s' % (index, time.time())
if not line:
print ur'line %s is empty "\t"' % index
continue
line = line.strip()
try:
imgs = line.split('\t')
if len(imgs) != 2:
print ur'line %s splite error' % index
continue
if not imgs[0] or not imgs[1]:
print ur'line %s img is empty' % index
continue
yield imgs
except:
print ur'line %s can not split by "\t"' % index lock = threading.Lock()
def loop(imgs):
print 'thread %s is running...' % threading.current_thread().name while True:
try:
with lock:
img_url, img_name = next(imgs)
except StopIteration:
break
try:
download(img_url, img_name)
except:
print 'exceptfail\t%s' % img_url
print 'thread %s is end...' % threading.current_thread().name img_gen = get_imgurl_generate() for i in range(0, thread_num):
t = threading.Thread(target=loop, name='LoopThread %s' % i, args=(img_gen,))
t.start()
python多线程下载文件的更多相关文章
- Python之FTP多线程下载文件之分块多线程文件合并
Python之FTP多线程下载文件之分块多线程文件合并 欢迎大家阅读Python之FTP多线程下载系列之二:Python之FTP多线程下载文件之分块多线程文件合并,本系列的第一篇:Python之FTP ...
- Python之FTP多线程下载文件之多线程分块下载文件
Python之FTP多线程下载文件之多线程分块下载文件 Python中的ftplib模块用于对FTP的相关操作,常见的如下载,上传等.使用python从FTP下载较大的文件时,往往比较耗时,如何提高从 ...
- python爬虫下载文件
python爬虫下载文件 下载东西和访问网页差不多,这里以下载我以前做的一个安卓小游戏为例 地址为:http://hjwachhy.site/game/only_v1.1.1.apk 首先下载到内存 ...
- 多线程下载文件,ftp文件服务器
1: 多线程下载文件 package com.li.multiplyThread; import org.apache.commons.lang3.exception.ExceptionUtils; ...
- 教你如何在 Android 使用多线程下载文件
# 教你如何在 Android 使用多线程下载文件 前言 在 Android 日常开发中,我们会经常遇到下载文件需求,这里我们也可以用系统自带的 api DownloadManager 来解决这个问题 ...
- java 多线程下载文件 以及URLConnection和HttpURLConnection的区别
使用 HttpURLConnection 实现多线程下载文件 注意GET大写//http public class MultiThreadDownload { public static void m ...
- java 多线程下载文件并实时计算下载百分比(断点续传)
多线程下载文件 多线程同时下载文件即:在同一时间内通过多个线程对同一个请求地址发起多个请求,将需要下载的数据分割成多个部分,同时下载,每个线程只负责下载其中的一部分,最后将每一个线程下载的部分组装起来 ...
- java 网络编程基础 InetAddress类;URLDecoder和URLEncoder;URL和URLConnection;多线程下载文件示例
什么是IPV4,什么是IPV6: IPv4使用32个二进制位在网络上创建单个唯一地址.IPv4地址由四个数字表示,用点分隔.每个数字都是十进制(以10为基底)表示的八位二进制(以2为基底)数字,例如: ...
- python多线程下载ts文件
# -*- coding: utf-8 -*- """ Created on Wed Aug 22 15:56:19 2018 @author: Administrato ...
随机推荐
- EVE-NG硬盘扩容,存储海量镜像
EVE-NG硬盘扩容,存储海量镜像 来源 http://blog.51cto.com/sms1107/1928453 一.查看当前磁盘使用情况 /dev/mapper/eve--ng--vg-root ...
- CF521D Shop 贪心
题意: \(n\)个数,有\(m\)个操作,形如: 1,将\(x_i\)改成\(val_i\) 2,将\(x_i\)加上\(val_i\) 3,将\(x_i\)乘上\(val_i\) 其中第\ ...
- C++11线程使用总结
std::thread 在 <thread> 头文件中声明,因此使用 std::thread 需包含 <thread> 头文件. <thread> 头文件摘要 &l ...
- 洛谷 P4721 【模板】分治 FFT 解题报告
P4721 [模板]分治 FFT 题目背景 也可用多项式求逆解决. 题目描述 给定长度为 \(n−1\) 的数组 \(g[1],g[2],\dots,g[n-1]\),求 \(f[0],f[1],\d ...
- Kerberos的白银票据详解
0x01白银票据(Silver Tickets)定义 白银票据(Silver Tickets)是伪造Kerberos票证授予服务(TGS)的票也称为服务票据.如下图所示,与域控制器没有AS-REQ 和 ...
- 在make php-5.5.5时提示没有X11/xpm.h,怎么解决!
yum install libXpm-devel在查询他的安装位置:#rpm -ql libXpm-devel/usr/bin/cxpm/usr/bin/sxpm/usr/include/X11/xp ...
- Amphetamine的cf日记
之前挂上的 今天填坑 2018.2.14 #462 A 给两个集合,B分别可以从一个集合中选一个数,B想乘积最大,A想最小,A可以删除一个第一个集合中的元素,问最小能达到多少. 这题..水死啦.我居然 ...
- 【bzoj2938】病毒
Portal -->bzoj2938 Solution 这题的话..一开始想的是不是上一个trie就消失了但是后来发现好像我还是太年轻qwq 比较容易联想到..AC自动机,多串匹配嘛 然后就.. ...
- dorado事件
//----------------------------------------------------------------------------// //校验实体数据是否填写if(enti ...
- poj1486 Sorting Slides
Sorting Slides Time Limit: 1000MS Memory Limit: 10000K Total Submissions: 4812 Accepted: 1882 De ...