初学Python多久,大多数都喜欢爬取妹子图片,今天我就给大家分享一下研究出来的代码,爬取动态加载图片的网站,并且保存到本地。让大家以后不必为这个难题而烦恼。不过这里首先说一下,如果大家也自己爬取动态加载的图片那种网站,建议先去爬取静态的,因为这个要简单的多,由浅而深嘛。
好了,现在我现了讲解一下关于爬取动态加载的图片,后面我会附上完整的代码。
这里我们我们需要导入几个库,urllib、requests、BeautifulSoup和re,代码很简单,但是这里主要用到正则表达式。不过这个很简单的,大家只需要去网上看一下基本教程就会。
今天我们就以爬取360网站的图片为例给大家分享想一下我的成果。这个是爬取美女图片的;
url = "http://image.so.com/i?src=360pic_strong&z=1&i=0&cmg=1e3ddcecc474bf6d0d486ca671c63d47&q=%E7%BE%8E%E5%A5%B3%E5%9B%BE%E7%89%87" html = requests.get(url).text #print html content = urllib.urlopen(url).read() soup = BeautifulSoup(content,"html.parser")
上述代码是一个网络爬虫最基本的代码,相当于框架,获取链接,打开,对HTML进行解析输出。这段代码和大家的是一样的,只是有一些喜欢写成函数调用。
clist = re.findall('http:\\\/\\\/p.*?\.jpg',html)
这段代码是采用采用了正在表达式获取链接,如下图:
这个采用正则表达式获得的效果;这个一看就知道不是图片链接,所以我们需要对其进行处理,但是里面有很的重复的,所以我们采用字典的方法,对其进行处理,下段代码就只字典的使用方法。
dic={} for i in clist: if i in dic.keys(): dic[i]+=1 else: dic[i]=1 name_list=[] num_list=[] for key in dic: name_list.append(key) num_list.append(dic[key])
采用替换的方法可以对上述图片链接进行处理。
b.append(name_list[i].replace("\/","/"))
得到正确的图片地址:
现在我们已经获取了正确的图片链接,接下来就是对其进行本地存储和下载:
urllib.urlretrieve(b[t],'C:\\Users\\ASUS\\Desktop\\txt\\img/%s.jpg' % x)
好了,接下来附上完整的代码:
# coding=utf-8 import urllib import requests from bs4 import BeautifulSoup import re url = "http://image.so.com/i?src=360pic_strong&z=1&i=0&cmg=1e3ddcecc474bf6d0d486ca671c63d47&q=%E7%BE%8E%E5%A5%B3%E5%9B%BE%E7%89%87" html = requests.get(url).text #print html content = urllib.urlopen(url).read() soup = BeautifulSoup(content,"html.parser") #print soup clist = re.findall('http:\\\/\\\/p.*?\.jpg',html) dic={} for i in clist: if i in dic.keys(): dic[i]+=1 else: dic[i]=1 name_list=[] num_list=[] for key in dic: name_list.append(key) num_list.append(dic[key]) #print (name_list[1]) b = [] i=1 while i<len(name_list): b.append(name_list[i].replace("\/","/")) i=i+1 for i in b: print i t=0 x=0 while t<len(b): urllib.urlretrieve(b[t],'C:\\Users\\ASUS\\Desktop\\txt\\img/%s.jpg' % x) t=t+1 x=x+1 print "正在爬取第"+str(x)+"张图片" print "爬取完成"好了,今天就分享到这里了,望各位能够喜欢,若需要爬取静态的,可以给我留言。谢谢!