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

yipeiwu_com5年前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爬虫文件下载图文教程

Python爬虫文件下载图文教程

而今天我们要说的内容是:如果在网页中存在文件资源,如:图片,电影,文档等。怎样通过Python爬虫把这些资源下载下来。 1、怎样在网上找资源: 就是百度图片为例,当你如下图在百度图片里搜...

python爬虫之百度API调用方法

python爬虫之百度API调用方法

调用百度API获取经纬度信息。 import requests import json address = input('请输入地点:') par = {'address': add...

python爬虫 使用真实浏览器打开网页的两种方法总结

1.使用系统自带库 os 这种方法的优点是,任何浏览器都能够使用, 缺点不能自如的打开一个又一个的网页 import os os.system('"C:/Program Files...

python爬虫刷访问量 2019 7月

看着自己少得可怜的访问量,突然有一个想用爬虫刷访问量的想法,主要也是抱着尝试的心态,学习学习。 其实市面上有一些软件可以代刷流量 比如 流量精灵,使用感确实比我们自己写的代码要好一些 第...

python实现简单爬虫功能的示例

python实现简单爬虫功能的示例

在我们日常上网浏览网页的时候,经常会看到一些好看的图片,我们就希望把这些图片保存下载,或者用户用来做桌面壁纸,或者用来做设计的素材。 我们最常规的做法就是通过鼠标右键,选择另存为。但有...