python 抓取天堂图片网中的图片

来源:互联网 发布:vfp编程 编辑:程序博客网 时间:2024/04/27 17:54

这里注意运用了BeautifulSoup,requests和urllib的下载模块:

具体代码如下:

#coding=utf-8import requestsfrom bs4 import BeautifulSoupimport reimport urllib.requestdef cbk(a,b,c):    '''''回调函数    @a:已经下载的数据块    @b:数据块的大小    @c:远程文件的大小    '''    per=100.0*a*b/c    if per>100:        per=100    print ('%.2f%%' % per)    print(" ")url = 'http://www.ivsky.com/tupian/meishishijie/'headers ={'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.104 Safari/537.36 Core/1.53.3427.400 QQBrowser/9.6.12513.400','Referer':'http://www.ivsky.com/tupian/qita/index_11.html'}html = requests.get(url,headers = headers)soup = BeautifulSoup(html.text,'html.parser')for i in range(0,12):    link = url +'/index_'+str(i)+'.html'    headers = {        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.104 Safari/537.36 Core/1.53.3427.400 QQBrowser/9.6.12513.400',        'Referer':'http://www.ivsky.com/tupian/qita/index_11.html'}    html = requests.get(link, headers=headers)    mess = BeautifulSoup(html.text, 'html.parser')    for page in mess.find_all('ul',class_='ali'):        for img in page.find_all('img'):            imgre = re.compile(r'src="(.*?\.jpg)" alt')            imglist = re.findall(imgre,html.text)            #imgurl = img.get('src')            #print imgurl            x = 0            for imgurl in imglist:                work_path = "E:/img/" + str(x) + ".jpg"                urllib.request.urlretrieve(imgurl,work_path,cbk)                x += 1

小编用的是python3.x所以urllib库后面要加.request才能正常运行。如果你使用的时python2.x,注意把import.urllib.request的.request删除。下面的urllib.request.urlretrieve(imgurl,work_path,cbk)改为urllib.urlretrieve(imgurl,work_path,cbk)。

如果出现图片链接锁,在headers中加上Referer就可以解决。

由于出现了只能下载一张图片的问题,所以小编改了一下代码。