使用 urllib2 从 URL 写入 PDF 文件
我正在尝试使用 python 的模块 urllib2 保存从网络服务器生成的动态 pdf 文件。 我使用以下代码从服务器获取数据并将该数据写入文件,以便将 pdf 存储在本地磁盘中:
import urllib2
import cookielib
theurl = 'https://myweb.com/?pdf&var1=1'
cj = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
opener.addheaders.append(('Cookie', cookie))
request = urllib2.Request(theurl)
print("... Sending HTTP GET to %s" % theurl)
f = opener.open(request)
data = f.read()
f.close()
opener.close()
FILE = open('report.pdf', "w")
FILE.write(data)
FILE.close()
此代码运行良好,但 adobe reader 无法很好地识别写入的 pdf 文件。如果我使用 Firefox 手动执行请求,我可以毫无问题地接收文件,并且可以毫无问题地可视化它。 比较接收到的 http 标头(firefox 和 urrlib),唯一的区别是名为“Transfer-Encoding = chunked”的 http 标头字段。该字段在 Firefox 中收到,但当我执行 urllib 请求时似乎没有收到该字段。 有什么建议吗?
I'm trying to save a dynamic pdf file generated from a web server using python's module urllib2.
I use following code to get data from server and to write that data to a file in order to store the pdf in a local disk.:
import urllib2
import cookielib
theurl = 'https://myweb.com/?pdf&var1=1'
cj = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
opener.addheaders.append(('Cookie', cookie))
request = urllib2.Request(theurl)
print("... Sending HTTP GET to %s" % theurl)
f = opener.open(request)
data = f.read()
f.close()
opener.close()
FILE = open('report.pdf', "w")
FILE.write(data)
FILE.close()
This code runs well but the written pdf file is not well recognized by adobe reader. If I do the request manually using firefox, I have no problems to receive the file and I can visualize it withouut problems.
Comparing the received http headers (firefox and urrlib) the only difference is a http header field called "Transfer-Encoding = chunked". This field is received in firefox but it seems that is not received when I do the urllib request.
Any suggestion?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
尝试更改
为
额外的“b”表示以二进制模式写入。当前您正在以 ASCII/文本模式编写二进制文件。
Try changing,
to
The extra 'b' indicates to write in binary mode. Currently you are writing a binary file in ASCII/text mode.