zl程序教程

您现在的位置是:首页 >  后端

当前栏目

Python网络编程 - 请求地址上的文件并下载

2023-09-11 14:16:56 时间

我们用到了requests库,由于是第三方的,必须下载

如果是python 2.x用下面命令

pip install requests

python 3.x用下面命令

easy_install requests

运行结果:

Searching for requests
Reading https://pypi.python.org/simple/requests/
Best match: requests 2.8.1
Downloading https://pypi.python.org/packages/source/r/requests/requests-2.8.1.tar.gz#md5=a27ea3d72d7822906ddce5e252d6add9
Processing requests-2.8.1.tar.gz

...

 

downloadFile.py

import requests
res = requests.get('http://www.gutenberg.org/cache/epub/1112/pg1112.txt')
res.raise_for_status()
playFile = open('RomeoAndJuliet.txt', 'wb')
for chunk in res.iter_content(100000):
    playFile.write(chunk)
playFile.close()

运行结果:

目录下会产生一个文件
RomeoAndJuliet.txt