python妹子图简单爬虫实例

yipeiwu_com5年前Python爬虫

本文实例讲述了python妹子图简单爬虫实现方法。分享给大家供大家参考。具体如下:

#!/usr/bin/env python
#coding: utf-8
import urllib
import urllib2
import os
import re
import sys
#显示下载进度
def schedule(a,b,c):
  '''''
  a:已经下载的数据块
  b:数据块的大小
  c:远程文件的大小
  '''
  per = 100.0 * a * b / c
  if per > 100 :
    per = 100
  print '%.2f%%' % per
#获取html源码
def getHtml(url):
  page = urllib.urlopen(url)
  html = page.read()
  return html
#下载图片
def downloadImg(html, num, foldername):
  picpath = '%s' % (foldername) #下载到的本地目录
  if not os.path.exists(picpath): #路径不存在时创建一个
    os.makedirs(picpath)
  target = picpath+'/%s.jpg' % num
  myItems = re.findall('<p><a href="http:\/\/www.mzitu.com/.*?" ><img src="(.*?)" alt=".*?" /></a></p>',html,re.S)
  print 'Downloading image to location: ' + target
  urllib.urlretrieve(myItems[0], target, schedule)
#正则匹配分页
def findPage(html):
  myItems = re.findall('<span>(\d*)</span>', html, re.S)
  return myItems.pop()
#正则匹配列表
def findList(html):
  myItems = re.findall('<h2><a href="http://www.mzitu.com/(\d*)" title="(.*?)" target="_blank">.*?</a></h2>', html, re.S)
  return myItems
#总下载
def totalDownload(modelUrl):
  listHtml5 = getHtml(modelUrl)
  listContent = findList(listHtml)
  for list in listContent:
    html = getHtml('http://www.mzitu.com/' + str(list[0]))
    totalNum = findPage(html)
    for num in range(1, int(totalNum)+1):
      if num == 1:
        url = 'http://www.mzitu.com/' + str(list[0])
        html5 = getHtml(url)
        downloadImg(html5, str(num), str(list[1]))
      else:
        url = 'http://www.mzitu.com/' + str(list[0]) + '/'+str(num)
        html5 = getHtml(url)
        downloadImg(html5, str(num), str(list[1]))
if __name__ == '__main__':
  listHtml = getHtml('http://www.mzitu.com/model')
  #这是其中一个模块的url,可以添加不同的模块url从而达到整站爬取。
  for model in range(1, int(findPage(listHtml))+1):
    if model == 1:
      modelUrl = 'http://www.mzitu.com/model'
      totalDownload(modelUrl)
    else:
      modelUrl = 'http://www.mzitu.com/model/page/' + str(model)
      totalDownload(modelUrl)
  print "Download has finished."

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

相关文章

Python HTML解析器BeautifulSoup用法实例详解【爬虫解析器】

本文实例讲述了Python HTML解析器BeautifulSoup用法。分享给大家供大家参考,具体如下: BeautifulSoup简介 我们知道,Python拥有出色的内置HTML解...

详解python selenium 爬取网易云音乐歌单名

详解python selenium 爬取网易云音乐歌单名

目标网站: 首先获取第一页的数据,这里关键要切换到iframe里 打印一下 获取剩下的页数,这里在点击下一页之前需要设置一个延迟,不然会报错。 结果: 一共37页,爬取完...

Python爬虫使用代理IP的实现

Python爬虫使用代理IP的实现

使用爬虫时,如果目标网站对访问的速度或次数要求较高,那么你的 IP 就很容易被封掉,也就意味着在一段时间内无法再进行下一步的工作。这时候代理 IP 能够给我们带来很大的便利,不管网站怎么...

零基础写python爬虫之使用Scrapy框架编写爬虫

零基础写python爬虫之使用Scrapy框架编写爬虫

网络爬虫,是在网上进行数据抓取的程序,使用它能够抓取特定网页的HTML数据。虽然我们利用一些库开发一个爬虫程序,但是使用框架可以大大提高效率,缩短开发时间。Scrapy是一个使用Pyth...

python爬虫之模拟登陆csdn的实例代码

python模拟登陆网页主要使用到urllib、urllib2、cookielib及BeautifulSoup等基本模块,当然进阶阶段我们还可以使用像requests等更高级一点的模块。...