Python爬虫学习笔记
  • Introduction
  • 爬虫简介
    • 1.1 了解网页结构
  • BeautifulSoup 解析网页
    • 2.1 BeautifulSoup 解析网页: 基础
    • 2.2 BeautifulSoup 解析网页: CSS
    • 2.3 BeautifulSoup 解析网页: 正则表达
    • 2.4 小练习: 爬百度百科
  • 更多请求/下载方式
    • 3.1 多功能的 Requests
    • 3.2 下载文件
    • 3.3 小练习: 下载美图
  • 加速你的爬虫
    • 4.1 加速爬虫: 多进程分布式
    • 4.2 加速爬虫: 异步加载 Asyncio
  • 高级爬虫
    • 5.1 高级爬虫: 让 Selenium 控制你的浏览器帮你爬
    • 5.2 高级爬虫: 高效无忧的 Scrapy 爬虫库
Powered by GitBook
On this page
  • 使用 urlretrieve
  • 使用 request

Was this helpful?

  1. 更多请求/下载方式

3.2 下载文件

import os
os.makedirs('./img/', exist_ok=True)

IMAGE_URL = "https://morvanzhou.github.io/static/img/description/learning_step_flowchart.png"

使用 urlretrieve

在 urllib 模块中, 提供了一个下载功能 urlretrieve.

输入下载地址 IMAGE_URL 和要存放的位置. 图片就会被自动下载过去

from urllib.request import urlretrieve
urlretrieve(IMAGE_URL, './img/image1.png')

使用 request

import requests
r = requests.get(IMAGE_URL)
with open('./img/image2.png', 'wb') as f:
    f.write(r.content)

如果要下载的是大文件, 比如视频等. requests 能下一点, 保存一点,而不是要全部下载完才能保存去另外的地方,这就是一个 chunk 一个 chunk 的下载.

使用 r.iter_content(chunk_size) 来控制每个 chunk 的大小, 然后在文件中写入这个 chunk 大小的数据.

r = requests.get(IMAGE_URL, stream=True)    # stream loading

with open('./img/image3.png', 'wb') as f:
    for chunk in r.iter_content(chunk_size=32):
        f.write(chunk)
Previous3.1 多功能的 RequestsNext3.3 小练习: 下载美图

Last updated 6 years ago

Was this helpful?