zoukankan      html  css  js  c++  java
  • 爬虫实战: 图片的批量爬取

    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('33[1;33m开始爬取图片: {imgurl}33[0m'.format(**locals()))
                self.save_photo(imgurl)
                
    
    
    
    if __name__ == '__main__':
        
        urls = ['http://www.netbian.com/index.htm']
        
        urls += ['http://www.netbian.com/index_{page}.htm'.format(**locals()) for page in range(2,10)]
        
        for page,url in enumerate(urls):
            print('33[1;32m开始爬取第 {} 页33[0m'.format(page+1))
            pp = SpiderPhoto(url)
            pp.start()
        

    5.个人小建议

      本人喜欢输出一些内容,比如现在爬取多少页,爬到那个item等等

      因为在爬取过程中,有时候会因为爬虫限制的问题导致脚本运行失败,会在不同的页面报错,

      这时可以提醒我们,给我们的爬虫设置一些现在,比如增加等待时间,利用多线程或者多进程的方式,

      减少爬虫中断的概率。

    欢迎大家讨论学习 ~

  • 相关阅读:
    服务器运维
    mysq配置
    PHP-FPM进程数的设定
    vsftpd 安装配置详细教程
    php-fpm性能优化
    如果不知道MySQL当前使用配置文件(my.cnf)的路径的解决方法
    搭建linux+nginx+mysql+php环境
    PHP 页面编码声明方法详解(header或meta)
    Linux内核的一些知识。
    Connector框架笔记
  • 原文地址:https://www.cnblogs.com/lmt921108/p/13550870.html
Copyright © 2011-2022 走看看