lmt921108

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(\'\033[1;33m开始爬取图片: {imgurl}\033[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(\'\033[1;32m开始爬取第 {} 页\033[0m\'.format(page+1))
        pp = SpiderPhoto(url)
        pp.start()
    

5.个人小建议

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

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

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

  减少爬虫中断的概率。

 

欢迎大家讨论学习 ~

分类:

技术点:

相关文章:

  • 2021-07-02
  • 2022-02-04
  • 2022-01-03
  • 2022-12-23
  • 2022-02-11
  • 2022-12-23
  • 2021-10-05
  • 2021-09-17
猜你喜欢
  • 2022-12-23
  • 2021-12-29
  • 2021-10-25
  • 2022-02-07
  • 2021-08-23
  • 2022-12-23
  • 2021-09-07
相关资源
相似解决方案