爬虫实战: 图片的批量爬取

1. 找好练习网站(不要恶意爬取,爬取前面10也即可,避免给网站造成压力)

  网站链接:http://www.netbian.com/index.htm

2.实现方法:

  本流程使用requests + bs4进行爬取

  python版本:python3.6(尽量不要使用python2)

3.爬取思路及注意实现:

  分析照片在网站上的真实链接

  照片是二进制文件,因此读取的时候是content,保存的时候是,wb模式

  如何定位照片元素是最重要的:个人建议学习bs4的select方法,简单好用(后续熟练之后,可以结合多种元素定位方法)

  爬虫建议使用chrome浏览器,简单好用。

爬虫实战: 图片的批量爬取

 4.完整脚本

#!/usr/bin/env python 
#-*- coding:utf-8 -*-

'''批量爬取网站照片
'''


import requests
from bs4 import BeautifulSoup


headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.149 Safari/537.36'
}


class SpiderPhoto(object):
    
    def __init__(self, url):
        self.url = url
        
    
    def get_soup(self):
        '''根据输入url获取soup
        '''
        try:
            response = requests.get(self.url, headers=headers)
            print(response)
            response.raise_for_status
            soup = BeautifulSoup(response.text, 'html.parser')
        except Exception as e:
            print('aaaaaaaa',e)
            soup = 'None'
        return soup

    
    def get_all_img_urls(self,soup):
        imgs = soup.select('div.list li a img')
        return [item['src'] for item in imgs]
    
    
    def save_photo(self,imgurl):
        res = requests.get(imgurl)
        name = imgurl.split('/')[-1]
        with open(name, 'wb') as fw:
            fw.write(res.content)
            
    
    def start(self):
        soup = self.get_soup()
        imgs = self.get_all_img_urls(soup)
        
        for imgurl in imgs:
            print('