python妹子图简单爬虫实例

yipeiwu_com6年前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基于BeautifulSoup实现抓取网页指定内容的方法

本文实例讲述了python基于BeautifulSoup实现抓取网页指定内容的方法。分享给大家供大家参考。具体实现方法如下: # _*_ coding:utf-8 _*_ #xiao...

Python多进程方式抓取基金网站内容的方法分析

本文实例讲述了Python多进程方式抓取基金网站内容的方法。分享给大家供大家参考,具体如下: 在前面这篇/post/162418.htm我们已经简单了解了”python的多进程”,现在我...

利用PyCharm Profile分析异步爬虫效率详解

利用PyCharm Profile分析异步爬虫效率详解

今天比较忙,水一下 下面的代码来源于这个视频里面提到的,github 的链接为:github.com/mikeckenned…(本地下载) 第一个代码如下,就是一个普通的 for 循环...

python使用webdriver爬取微信公众号

本文实例为大家分享了python使用webdriver爬取微信公众号的具体代码,供大家参考,具体内容如下 # -*- coding: utf-8 -*- from seleniu...

Python爬虫实现百度图片自动下载

Python爬虫实现百度图片自动下载

制作爬虫的步骤 制作一个爬虫一般分以下几个步骤: 分析需求分析网页源代码,配合开发者工具编写正则表达式或者XPath表达式正式编写 python 爬虫代码 效果预览 运行效果如下:...