我正在尝试使用 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()
此代码运行良好,但编写的 pdf 文件无法被 adobe reader 很好地识别。如果我使用 firefox 手动执行请求,我可以毫无问题地接收文件,并且可以毫无问题地将其可视化。 比较接收到的 http header (firefox 和 urrlib),唯一的区别是名为“Transfer-Encoding = chunked”的 http header 字段。该字段在 firefox 中收到,但似乎在我执行 urllib 请求时未收到。 有什么建议吗?
最佳答案
尝试改变,
FILE = open('report.pdf', "w")
到
FILE = open('report.pdf', "wb")
额外的'b'表示以二进制模式写入。目前您正在以 ASCII/文本模式编写二进制文件。
关于python - 使用 urllib2 从 URL 写入 PDF 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5627083/