Python使用爬虫抓取美女图片并保存到本地的方法【测试可用】

yipeiwu_com6年前Python爬虫

本文实例讲述了Python使用爬虫抓取美女图片并保存到本地的方法。分享给大家供大家参考,具体如下:

图片资源来自于www.qiubaichengren.com

代码基于Python 3.5.2

友情提醒:血气方刚的骚年。请

谨慎阅图!
谨慎阅图!!
谨慎阅图!!!

code:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import urllib
import urllib.request
import re
from urllib.error import URLError
class QsSpider:
  def __init__(self):
    self.user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'
    self.header = {'User-Agent': self.user_agent}
    self.save_dir = './pic'
    self.url = 'http://www.qiubaichengren.com/%s.html'
  def start(self):
    for i in range(1, 10):
      self.load_html(str(i))
  def load_html(self, page):
    try:
      web_path = self.url % page
      request = urllib.request.Request(web_path, headers=self.header)
      with urllib.request.urlopen(request) as f:
        html_content = f.read().decode('gb2312')
        # print(html_content)
        self.pick_pic(html_content)
    except URLError as e:
      print(e.reason)
    return
  def save_pic(self, img):
    print(img)
    save_path = self.save_dir + "/" + img.replace(':', '@').replace('/', '_')
    if not os.path.exists(self.save_dir):
      os.makedirs(self.save_dir)
    print(save_path)
    urllib.request.urlretrieve(img, save_path)
    pass
  def pick_pic(self, html_content):
    regex = r'src="(http:.*?\.(?:jpg|png|gif))'
    patten = re.compile(regex)
    pic_path_list = patten.findall(html_content)
    for i in pic_path_list:
      self.save_pic(str(i))
      print(i)
spider = QsSpider()
spider.start()

代码运行后可得到如下N多大饱眼福的美女图:

更多关于Python相关内容可查看本站专题:《Python Socket编程技巧总结》、《Python正则表达式用法总结》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python入门与进阶经典教程》及《Python文件与目录操作技巧汇总

希望本文所述对大家Python程序设计有所帮助。

相关文章

Python中Scrapy爬虫图片处理详解

下载图片 下载图片有两种方式,一种是通过 Requests 模块发送 get 请求下载,另一种是使用 Scrapy 的 ImagesPipeline 图片管道类,这里主要讲后者。 安装...

Python使用爬虫爬取静态网页图片的方法详解

Python使用爬虫爬取静态网页图片的方法详解

本文实例讲述了Python使用爬虫爬取静态网页图片的方法。分享给大家供大家参考,具体如下: 爬虫理论基础 其实爬虫没有大家想象的那么复杂,有时候也就是几行代码的事儿,千万不要把自己吓倒了...

python&MongoDB爬取图书馆借阅记录

python&MongoDB爬取图书馆借阅记录

直接上需求和代码 首先是需要爬取的链接和网页:http://211.81.31.34/uhtbin/cgisirsi/x/0/0/57/49?user_id=LIBSCI_ENGI&pa...

解决Python 爬虫URL中存在中文或特殊符号无法请求的问题

这种问题,初学者应该都会遇到,分享给大家做个参考! from urllib.parse import quote import string #解决请求路径中含义中文或特殊字符 u...

Python实现的爬取豆瓣电影信息功能案例

Python实现的爬取豆瓣电影信息功能案例

本文实例讲述了Python实现的爬取豆瓣电影信息功能。分享给大家供大家参考,具体如下: 本案例的任务为,爬取豆瓣电影top250的电影信息(包括序号、电影名称、导演和主演、评分以及经典台...