gpt4 book ai didi

python - 如何在 python 中使用 web URL 下载文件?通过浏览器下载但不能通过 python 的请求下载

转载 作者:太空宇宙 更新时间:2023-11-04 01:45:16 24 4
gpt4 key购买 nike

如果在浏览器(Firefox、Chrome 等)中输入 URL,文件就会被下载。但是当我尝试使用 python 的 requestsurllib 库下载相同的文件(使用相同的 URL)时,我没有得到任何响应。

网址:https://www.nseindia.com/products/content/sec_bhavdata_full.csv (引用页码:https://www.nseindia.com/products/content/equities/equities/eq_security.htm)

我尝试过的:

import requests
eqfile = requests.get('https://www.nseindia.com/products/content/sec_bhavdata_full.csv')

没有回应。然后尝试了以下

temp = requests.get('https://www.nseindia.com/products/content/equities/equities/eq_security.htm')

还是没有反应。

从这样的 URL(网络服务器)下载文件的最佳方式是什么?

最佳答案

如果我使用类似于真实 Web 浏览器使用的 header User-Agent header ,那么我可以下载它。

import requests

headers = {'User-Agent': 'Mozilla/5.0'}
url = 'https://www.nseindia.com/products/content/sec_bhavdata_full.csv'

r = requests.get(url, headers=headers)
#print(r.content)

with open('sec_bhavdata_full.csv', 'wb') as fh:
fh.write(r.content)

门户网站经常检查此 header 以阻止请求或专门为您的浏览器/设备格式化 HTML。但是 requests(和 urllib.request)在此 header 中发送 "python ..."

许多门户网站只需要 'User-Agent': 'Mozilla/5.0' 来发送内容,但其他门户网站可能需要完整的标题 User-Agent 甚至其他标题,例如 ReferrerAcceptAccept-EncodingAccept-Language。您可以在页面 https://httpbin.org/get 上查看浏览器使用的 header

来自真实浏览器

关于python - 如何在 python 中使用 web URL 下载文件?通过浏览器下载但不能通过 python 的请求下载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59205601/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com