引言

一、Python图片抓取的准备工作

1. 安装Python环境

首先,确保你的计算机上已经安装了Python环境。可以从Python官方网站下载并安装最新版本的Python。

2. 安装抓取库

Python中有很多用于网络爬虫的库,如requests、BeautifulSoup、Scrapy等。以下列举一些常用的库:

  • requests:用于发送HTTP请求,获取网页内容。
  • BeautifulSoup:用于解析HTML和XML文档,提取所需信息。
  • Scrapy:一个强大的网络爬虫框架,可以方便地实现图片抓取。

你可以使用pip命令安装这些库:

pip install requests
pip install beautifulsoup4
pip install scrapy

二、Python图片抓取的基本流程

1. 确定目标网站

2. 发送HTTP请求

使用requests库发送HTTP请求,获取目标网页的HTML内容。

import requests

url = 'http://example.com'
response = requests.get(url)
html_content = response.text

3. 解析HTML内容

from bs4 import BeautifulSoup

soup = BeautifulSoup(html_content, 'html.parser')
img_tags = soup.find_all('img')

4. 下载图片

for img in img_tags:
    img_url = img.get('src')
    img_response = requests.get(img_url)
    img_content = img_response.content
    img_name = img_url.split('/')[-1]
    with open(img_name, 'wb') as f:
        f.write(img_content)

三、使用Scrapy实现图片抓取

import scrapy

class MySpider(scrapy.Spider):
    name = 'myspider'
    start_urls = ['http://example.com']

    def parse(self, response):
        img_tags = response.css('img::attr(src)').getall()
        for img_url in img_tags:
            yield scrapy.Request(img_url, self.save_image)

    def save_image(self, response):
        img_name = response.url.split('/')[-1]
        with open(img_name, 'wb') as f:
            f.write(response.body)

# 启动Scrapy爬虫
from scrapy.crawler import CrawlerProcess

process = CrawlerProcess()
process.crawl(MySpider)
process.start()

四、总结