python学习之爬虫脚本

python3.6

自己仿照网上的模板写了个爬虫脚本,可以爬mm图片呦。下面是代码和注释

#导入re模块,用来使用正则

分享之前我还是要推荐下我自己建的Python开发学习群:628979297,群里都是学Python开发的,如果你正在学习Python ,小编欢迎你加入,今天分享的这个案例已经上传到群文件,大家都是软件开发党,不定期分享干货(只有Python软件开发相关的),包括我自己整理的一份2018最新的Python进阶资料和高级开发教程,欢迎进阶中和进想深入Python的小伙伴。

import re

#导入urllib.request模块,打开网页源码用

import urllib.request

#导入os模块,来自动创建保存路径

import os

#导入time模块,用来实现下面的每爬一次睡几秒

import time

#创建一个全局变量,用以实现图片保存后连续计数命名

num=0

#下面是创建保存路径的文件夹

path=’D:\爬虫图片\mm’

dir=os.path.exists(path)

if not dir:

os.makedirs(path)

def getHtml(url):

#伪装headers,反反爬

user_agent=’Mozilla/5.0 (Windows NT 10.0; Win64; X64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36′

headers={‘User-Agent’:user_agent}

req=urllib.request.Request(url,headers=headers)

page=urllib.request.urlopen(req)

html=page.read()

rehtml=str(html)

reg=r’charset=(.+?)”‘ #自动识别网站源码的编码方式

imgre=re.compile(reg)

imglist=re.findall(imgre,rehtml)

#print(‘page coded by %s’ %imglist)

code=’gbk’ #此处本来要写成=imglist[0],但实际爬图片的时候发现网站上标注的编码方式并不一定好使,而是要写另外一个兼容这个编码方式的编码,所以我就直接给固定了,上面也白自动识别了。具体说明可以参照下面网址: http://www.crifan.com/summary_python_unicodedecode_error_possible_reasons_and_solutions/

html=html.decode(‘%s’ %code)

return html

def getImg(html):

#从海量网站代码中设置过滤正则表达式,以找到图片地址。

reg=r’1\)” src=”(.+?\.jpg)”‘

imgre=re.compile(reg)

imglist=re.findall(imgre,html)

#调用上面设置的全局变量,以计数

global num

for imgurl in imglist:

#保存图片

urllib.request.urlretrieve(imgurl,path+’\mm%s.jpg’ %num)

num+=1

print(num)

for i in range(2330,2390): #根据网站源代码,连续怕N多网址

a=str(i)

url=’http://www.mm131.com/xinggan/’+a+’.html’

#下面比较重要,因为上面设置的是怕连续网址,但有时网站上有些网址并不存在,下面是判断网址是否存在,如果存在就怕图片,不存在就不浪费时间了

try:

html=getHtml(url)

print(getImg(html))

except urllib.error.HTTPError as e:

if e.code==404:

print(‘cant find %s’ %url)

    原文作者:Python爬虫学习
    原文地址: https://www.jianshu.com/p/b78fd74394ba
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞