使用python从php服务器下载pdf文件



我正在尝试下载位于PHP服务器上的pdf文件(少数可以是word文件,非常罕见)。似乎在服务器上,pdf的编号从1增加到14000。pdf文件可以通过以下链接下载:http://ppmoe.dot.ca.gov/des/oe/awards/bidsum/dl.php?id=X,其中X是[1,14000]范围内的数字。我使用以下代码X = 200,然后我可以循环遍历所有[1,14000]值,以将所有文件保存在特定文件夹中:

import requests
url = "http://ppmoe.dot.ca.gov/des/oe/awards/bidsum/dl.php?id=200"
s = requests.Session()
response = s.get(url)
with open("file200.pdf", "w") as f:
f.write(response.content)
f.close()

但是它返回以下错误:

Traceback (most recent call last):
File "<stdin>", line 2, in <module>
TypeError: write() argument must be str, not bytes

我不确定我们是否可以使用python下载这些文件,PHP对我来说是陌生的。谢谢!

您需要将b添加到参数中,以便将数据作为二进制数据写入文件(response.content包含字节,而不是字符串):

with open("file200.pdf", "wb") as f:
f.write(response.content)
f.close()

最新更新