简体   繁体   English

从重定向链接python下载文件

[英]Downloading file from redirection link python

I am trying to make a simple program that will help with the confusing part of rooting. 我正在尝试制作一个简单的程序,以帮助解决生根的混乱问题。

I need to download the file from tiny.cc/latestmagisk 我需要从tiny.cc/latestmagisk下载文件

I am using this python code 我正在使用此python代码

import request
url = tiny.cc/latestmagisk

r = request.get(url)
r.content

The content it returns is the usual 403 Forbidden for nginx 它返回的内容是nginx通常禁止使用的403

I need this to work with the shortened URL is there anyway to make that happen? 我需要使用此方法来处理缩短的URL,是否有办法做到这一点?

Contrary to the other answer, you really should use requests for this as requests has better support for redirects. 与其他答案相反,您确实应该为此使用requests ,因为requests对重定向具有更好的支持。

For getting a page through a redirect from requests: 通过请求重定向获取页面:

r=requests.get(url, allow_redirects=True)

For downloading files through redirects: 通过重定向下载文件:

r = requests.get(url, allow_redirects=True, stream=True)
with open(filename, 'wb') as f:
    for chunk in r.iter_content(chunk_size=1024): 
        if chunk: f.write(chunk)

However, in this case, either tiny.cc or XDA does not allow a simple requests.get; 但是,在这种情况下,tiny.cc或XDA都不允许简单的request.get;。 the 403 forbidden is likely due to the User-Agent or other intrinsic header as this method works well with bit.ly and other shortlink generators. 禁止使用403可能是由于User-Agent或其他内部标头,因为此方法与bit.ly和其他shortlink生成器配合得很好。 You may need to fake headers. 您可能需要伪造标题。

its's not necessary to import request lib 导入请求库不是必需的
all you need to do is import ssl, urllib and pass ssl._create_unverified_context() as context to the server while you're sendig a request! 您需要做的就是import ssl, urllib并在发送请求时将ssl._create_unverified_context()作为上下文传递给服务器!
your code should be look like this: 您的代码应如下所示:

import ssl, urllib

certcontext = ssl._create_unverified_context()
f = open('image.jpg','wb') #creating placeholder

#creating image from url and saving it as `image.jpg`!
f.write(urllib.urlopen("https://i.stack.imgur.com/IKh7E.png", context=certcontext).read())

f.close()


note: it will save the image as image.jpg file .. 注意:它将图像保存为image.jpg文件..

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM