python urllib / requests fails to download file but browser does(Python urllib/Requests下载文件失败,但浏览器下载失败)
本文介绍了Python urllib/Requests下载文件失败,但浏览器下载失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试下载此zip file。 该压缩文件可通过Chrome正确下载,但使用请求或urllib失败,出现错误400 Bad Request。
>> import requests
>> import urllib
>> url = 'http://prd-enforce-xfr-02.dol.gov/../data_catalog/EBSA/ebsa_ocats_20150703.csv.zip'
>> r = requests.get(url)
>> r.ok
False
>> r.headers
{'content-length': '254', 'content-encoding': 'gzip', 'vary': 'Accept-Encoding', 'server': 'Apache/2.2.14 (Ubuntu)', 'connection': 'close', 'date': 'Tue, 07 Jul 2015 20:39:55 GMT', 'content-type': 'text/html; charset=iso-8859-1'}
>> r
<Response [400]>
>> r.text
u'<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>400 Bad Request</title>
</head><body>
<h1>Bad Request</h1>
<p>Your browser sent a request that this server could not understand.<br />
</p>
<hr>
<address>Apache/2.2.14 (Ubuntu) Server at prd-enforce-xfr-02.dol.gov Port 80</address>
</body></html>
'
>> z = urllib.urlopen(url)
>> z.read()
'<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>400 Bad Request</title>
</head><body>
<h1>Bad Request</h1>
<p>Your browser sent a request that this server could not understand.<br />
</p>
<hr>
<address>Apache/2.2.14 (Ubuntu) Server at prd-enforce-xfr-02.dol.gov Port 80</address>
</body></html>
'
我尝试过的事情(失败了):
欺骗用户代理标头。
使用请求会话保存Cookie
。
推荐答案
删除无关的/..从URL。它可以在浏览器中工作,因为浏览器会为您标准化URL。如果没有/..这可以很好地处理urllib或请求。
这篇关于Python urllib/Requests下载文件失败,但浏览器下载失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
织梦狗教程
本文标题为:Python urllib/Requests下载文件失败,但浏览器下载失败
基础教程推荐
猜你喜欢
- 比较两个文本文件以找出差异并将它们输出到新的文本文件 2022-01-01
- 对多索引数据帧的列进行排序 2022-01-01
- 在 Django Admin 中使用内联 OneToOneField 2022-01-01
- Kivy 使用 opencv.调整图像大小 2022-01-01
- 究竟什么是“容器"?在蟒蛇?(以及所有的 python 容器类型是什么?) 2022-01-01
- 在 Python 中将货币解析为数字 2022-01-01
- matplotlib 设置 yaxis 标签大小 2022-01-01
- Python 中是否有任何支持将长字符串转储为块文字或折叠块的 yaml 库? 2022-01-01
- Python,确定字符串是否应转换为 Int 或 Float 2022-01-01
- kivy 应用程序中的一个简单网页作为小部件 2022-01-01
