简体   繁体   English

在python 3中从Web服务下载文件

[英]download file from web service in python 3

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. 我确实看到了几种使用Python从HTTP / HTTPS下载文件的方法,但是对于所有这些,您都需要知道确切的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. 我正在尝试从Web服务下载,并且URL具有为下载文件而发送的方法和后置参数,但我不知道该发送什么URL。 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? 打印语句看起来好像正在阅读PDF,但是我想将其保存在某个地方,找不到任何方法吗? 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)

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

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