在使用Python编程进行数据集下载时,遇到程序突然中断的情况并不罕见。这种情况通常由多种因素引起,如网络不稳定、API请求数量限制或SSL握手失败,尤其是SSL握手失败导致下载停滞都是属于我们工作中常见的了。此类问题,我们可以采取一些措施来解决,以此来推进我们的项目进度。
首先,我们来说说网络不稳定的问题。网络不稳定通常表现为连接中断、速度缓慢或无法建立连接,我们能很直观的看出来。这种情况下,可能是由于我们的网络环境复杂、互联网流量的变化、或者隔墙防火墙等问题导致。
处理网络不稳定的问题,我们可以试试:
import time
import requests
from requests.adapters import HTTPAdapter
from requests.packages.urllib3.util.retry import Retry
def download_with_retry(url, path, retries=5):
session = requests.Session()
retry = Retry(total=retries, backoff_factor=1, status_forcelist=[429, 500, 502, 503, 504])
adapter = HTTPAdapter(max_retries=retry)
session.mount('http://', adapter)
session.mount('https://', adapter)
try:
response = session.get(url, stream=True)
with open(path, 'wb') as f:
for chunk in response.iter_content(1024):
if chunk:
f.write(chunk)
except requests.exceptions.RequestException as e:
print(f"Failed to download file: {e}")
API请求数量限制通常由服务提供商(如Kaggle)设定,以防止过度使用其服务。这种限制会导致当请求过多时,会碰到“手滑”被暂时屏蔽的问题。
针对API请求数量限制的这个问题,我们可以尝试:
import time
def request_with_rate_limiting(url, interval=2):
response = requests.get(url)
time.sleep(interval) # Wait for the interval period
return response
以下是部分代码,大家可以参考一下:
import os
import time
import requests
from requests.adapters import HTTPAdapter
from requests.packages.urllib3.util.retry import Retry
PROXY_POOL = [
"https://www.qg.net:8080",
# 青果网络的代理IP,更多代理IP请登录青果网络获取
]
def get_random_proxy():
return {"http": PROXY_POOL[time.time() % len(PROXY_POOL)], "https": PROXY_POOL[time.time() % len(PROXY_POOL)]}
def download_file_with_proxy(url, path, proxies, retries=5):
session = requests.Session()
retry = Retry(total=retries, backoff_factor=1, status_forcelist=[429, 500, 502, 503, 504])
adapter = HTTPAdapter(max_retries=retry)
session.mount('http://', adapter)
session.mount('https://', adapter)
headers = {}
if os.path.exists(path):
existing_file_size = os.path.getsize(path)
headers['Range'] = f'bytes={existing_file_size}-'
else:
existing_file_size = 0
response = session.get(url, headers=headers, proxies=get_random_proxy(), stream=True)
total_size = int(response.headers.get('content-length', 0)) + existing_file_size
with open(path, 'ab') as file: # Open in append mode
for chunk in response.iter_content(chunk_size=1024):
if chunk:
file.write(chunk)
# 使用青果网络代理IP进行下载
download_file_with_proxy('https://kaggle.com/api/v1/datasets/download_url', 'largefile.zip', PROXY_POOL)
希望这些方法能在你的项目中有所助益,帮助你解决我们在使用Python编程进行数据集下载时,遇到程序突然中断的情况。如果还有后续的疑问,也可以在评论区给我留言,如果我看到了会及时回复。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。