在这篇博客中:
http://blog.csdn.net/Innovation_Z/article/details/51106601
,作者利用递归方法解决了urlretrieve下载文件不完整的方法,其代码如下:
def auto_down(url,filename):
urllib.urlretrieve(url,filename)
except urllib.ContentTooShortError:
print 'Network conditions is not good.Reloading.'
auto_down(url,filename)
但是经笔者测试,下载文件出现urllib.ContentTooShortError且重新下载文件会存在用时过长的问题,而且往往会尝试好几次,甚至十几次,偶尔会陷入死循环,这种情况是非常不理想的。为此,笔者利用socket模块,使得每次重新下载的时间变短,且避免陷入死循环,从而提高运行效率。
以下为代码:
import socket
import urllib.request
#设置超时时间为30s
socket.setdefaulttimeout(30)
#解决下载不完全问题且避免陷入死循环
urllib.request.urlretrieve(url,image_name)
except socket.timeout:
count = 1
while count <= 5:
urllib.request.urlretrieve(url,image_name)
break
except socket.timeout:
err_info = 'Reloading for %d time'%count if count == 1 else 'Reloading for %d times'%count
print(err_info)
count += 1
if count > 5:
print("downloading picture fialed!")
本次分享到此结束,如有不足之处,还请批评指正!欢迎大家交流~~
注意:本人现已开通两个微信公众号: 因为Python(微信号为:python_math)以及轻松学会Python爬虫(微信号为:easy_web_scrape), 欢迎大家关注哦~~
作者:剑与星辰
来源:CSDN
原文:https://blog.csdn.net/jclian91/article/details/77513289
版权声明:本文为博主原创文章,转载请附上博文链接!
原文链接:www.baidu.com
python爬虫之urllib,伪装,超时设置,异常处理的方法Urllib1. Urllib.request.urlopen().read().decode()返回一个二进制的对象,对这个对象进行read()操作,可以得到一个包含网页的二进制字符串,然后用decode()解码成html源码2. urlretrieve()将一个网页爬取到本地3. urlclearup()清除 urlretrieve...
初学者想学写个爬虫,边学边写想要下载一张 Y 站的图片,代码为urllib.request.urlopen('http://xxx.jpg').read()其中 url 是可以正常访问的。图片不大,浏览器打开只需要几秒(排除缓存原因)。但在 python 中下载它却需要 30+秒,将下载到的数据写出为文件是可以正常查看的那么问题来了,究竟是什么原因导致下载一张图片那么慢呢?请问是还有什么地方需要配...
# create the object, assign it to a variable
proxy = request.ProxyHandler({
'http': '127.0.0.1:8118',
'https': '127.0.0.1:8118',
# construct a new opener using your proxy settings
在使用Biopython 进行PDB文件下载时, 当文件多了, 经常性会卡死. 这种卡死的问题往往可以通过设置超时timeout值来控制. 当连接时间大于超时时间, 就会发生超时错误, 从而避免卡死的问题.经查源代码, Biopython使用urllib库的urlretrieve方法进行文件的下载. 经查, 该方法并没有timeout参数可以控制超时. 因此不能简单地避免这个问题.想运用reque...
参考 http://cn.python-requests.org/zh_CN/latest/user/advanced.html#streaming-requestsimport urllib,os# opener=urllib.request.build_opener()# opener.addheaders=[('User-Agent','Mozilla/5.0 (Windows NT 6.1...
python socket.error: [Errno 10054] 远程主机强迫关闭了一个现有的连接。问题解决方案:前几天使用python读取网页。因为对一个网站大量的使用urlopen操作,所以会被那个网站认定为攻击行为。有时就不再允许下载。导致urlopen()后,request.read()一直卡死在那里。最后会抛出errno 10054.这个错误是connection reset by ...
问题: 我们使用urllib.urlretrieve(url,filename)时经常遇到下载到一半时,出现urllib.ContentTooShortError错误。这是因为文件下载不完全导致的错误。
解决: 我们可以使用捕捉错误解决这个问题,例如:
urllib.urlretrieve(url,filename)
except urllib.Cont
结合在网上找到的解决办法,成功解决了在使用urlretrieve下载文件的过程中所遇到了一些问题:urlretrieve下载文件不完全且下载时长过长陷入死循环
参考地址1、参考地址2
# -*- coding: utf-8 -*-
import pathlib
import re
import socket
import time
import urllib.request
url = "ht...
我们使用urllib.urlretrieve(url,filename)时经常遇到下载到一半时,出现urllib.ContentTooShortError错误。这是因为文件下载不完全导致的错误。
urllib.urlretrieve(url,filename)等待时间过长,导致程序死循环或者卡死。
import socket
import urllib.request