从python 3中的web服务下载文件 [英] download file from web service in python 3

查看:488
本文介绍了从python 3中的web服务下载文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Python中看到一些从HTTP / HTTPS下载文件的方法,但是对于所有这些方法,您需要知道确切的URL。我正在尝试从Web服务下载,URL中有方法和发布参数以便下载文件,我无法弄清楚要发送的URL。这是代码片段:

  url ='https://www.example123.com'
params = { 'user':'username','pass':'password','method':'getproject','getPDF':'true'}
data = urllib.parse.urlencode(params)
data = data.encode('utf-8')
request = urllib.request.Request(url,data)
response = urllib.request.urlopen(request)
xdata = response。 read()
print(xdata)

打印语句看起来好像正在阅读PDF ,但是我想把它保存在某个地方,找不到任何办法呢?以下是打印响应的开始:

  b'%PDF-1.6\r%\xe2\xe3\\ \\ xcf\xd3\r\\\
12 0 obj\r

解决方案

你必须打开一个文件并写信给它。现在,你只是将它存储在字符串变量中。

  with open('yourfile.pdf','w')作为f:
f.write(xdata)


I do see a few methods of downloading a file from HTTP/HTTPS in Python, but for all of these you need to know the exact URL. I'm trying to download from a web service and the URL has methods and post arguments that are sent in order to download the file, I can't figure out what the URL is to send. This is the code snippet:

url = 'https://www.example123.com'
params = { 'user' : 'username', 'pass' : 'password', 'method' : 'getproject', 'getPDF' : 'true' }
data = urllib.parse.urlencode(params)
data = data.encode('utf-8')
request= urllib.request.Request(url, data)
response = urllib.request.urlopen(request)
xdata = response.read()
print(xdata)

The print statement looks as though it's reading the PDF, but I want to save it somewhere and can't find any way to do that? Here is the beginning of the print response:

b'%PDF-1.6\r%\xe2\xe3\xcf\xd3\r\n12 0 obj\r<</Lin

解决方案

You have to open a file and write to it. Right now, you are just storing it in a string variable.

with open('yourfile.pdf', 'w') as f:
    f.write(xdata)

这篇关于从python 3中的web服务下载文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆