如何使用请求模块从 Web 下载文件? [英] How do I download files from the web using the requests module?

查看:39
本文介绍了如何使用请求模块从 Web 下载文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用以下代码将网页数据下载到我硬盘上的 samplefile.txt:

I'm trying to download a webpage data to samplefile.txt on my hard drive using the following code:

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

playFile.close()

代码运行没有错误,但 samplefile.txt 中没有任何变化.我该如何解决?谢谢

The code runs without errors but nothing changes in samplefile.txt. How do I fix this? Thanks

推荐答案

import requests 
res = requests.get('http://www.gutenberg.org/cache/epub/1112/pg1112.txt')
res.raise_for_status()
open('samplefile.txt', 'wb').write(res.content)

这是文件samplefile.txt"""罗密欧与朱丽叶的古腾堡计划电子书,威廉·莎士比亚着...."""

This is file samplefile.txt """The Project Gutenberg EBook of Romeo and Juliet, by William Shakespeare .... """

这篇关于如何使用请求模块从 Web 下载文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆