This article mainly introduces the simple crawling of the python girl chart. The example analyzes the page source code acquisition, progress display, regular expression matching, and other skills involved in the Python crawler program, for more information about how to implement simple crawling, see the example in this article. Share it with you for your reference. The details are as follows:
#! /Usr/bin/env python # coding: utf-8import urllibimport urllib2import osimport reimport sys # display download progress def schedule (a, B, c): ''': downloaded data block B: data block size c: Remote File Size ''' per = 100.0 * a * B/c if per> 100: per = 100 print '%. 2f % '% per # obtain html source code def getHtml (url): page = urllib. urlopen (url) html = page. read () return html # download image def downloadImg (html, num, foldername): picpath = '% s' % (foldername) # download to the local directory if not OS. path. exists (picpath): # create an OS when the path does not exist. makedirs (picpath) target = picpath + '/%s.jpg' % num myItems = re. findall ('', Html, re. s) print 'downloading image to location: '+ target urllib. urlretrieve (myItems [0], target, schedule) # Regular Expression matching paging def findPage (html): myItems = re. findall ('(\ d *)', html, re. s) return myItems. pop () # regular expression match list def findList (html): myItems = re. findall ('. *? ', Html, re. s) return myItems # Total download 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 ') # This is the url of a module. You can add different module URLs to achieve full-site crawling. 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 ."
I hope this article will help you with Python programming.