用python爬取图片的一点小结 - Go语言中文社区

用python爬取图片的一点小结


一、原理小结

最近在学习用python的爬虫爬取网络上的图片,制作数据集并用于后续的一些实验。看了很多关于python爬取图片的介绍,并验证了相关代码,先推荐几个介绍比较好的爬虫过程:

[1]小白爬虫第一弹之抓取妹子图(这篇博客的过程讲解的非常详细)

[2]Python爬虫之——爬取妹子图片(静态图片爬取)

[3]利用python爬取网页图片(动态加载图片的爬取)

总体上来说,爬虫的主要思路大致可以描述为:

1. 判断待爬取网页中的图片是静态还是动态,并利用开发者选项F12查找图片的源

2. python中导入相关模块,读取解析页面文件

3. 分析所有图片的位置特点,并用python进行查找

4. 设置下载路径,对找到的图像进行批量下载

其中最为关键的还是第1步,即对页面的分析,找到相关的图像位置。

二、动态图片的爬取

动态图片是指像百度图片搜索,搜狗搜图等搜索引擎的搜索结果,这类图片的最大特点是,每次只加载一批图片,每向下拉都会继续加载新的图像,关于这类图片的爬取可以参考[3]。这里[3]给出一个可以直接运行的代码:

# 导入相关的库
import requests
import json
import urllib
import os

# 爬取图片的保存路径
output_dir = "./images/"


# 爬取搜狗搜图的函数
def getSogouImag(category, length, path):
    '''
    参数category:指要爬取图片的类型,字符串格式,如:'壁纸'
    参数length:指要爬取多少张,整型
    参数path:存储路径
    '''
    n = length
    cate = category
    #http://pic.sogou.com/pics/channel/getAllRecomPicByTag.jsp?category=%E7%BE%8E%E5%A5%B3&tag=%E5%85%A8%E9%83%A8&start=0&len=15
    imgs = requests.get('http://pic.sogou.com/pics/channel/getAllRecomPicByTag.jsp?category='+cate+'&tag=%E5%85%A8%E9%83%A8&start=0&len='+str(n)+'&width=1536&height=864')
    jd = json.loads(imgs.text)
    jd = jd['all_items']
    imgs_url = []
    for j in jd:
        imgs_url.append(j['pic_url'])
    m = 0
    for img_url in imgs_url:
            print('***** '+str(m)+'.jpg *****'+'   Downloading...')
            urllib.request.urlretrieve(img_url, path+str(m)+'.jpg')
            m = m + 1
    print('Download complete!')

# 检查是否存在路径,若不存在,则创建
if not os.path.exists(output_dir):
    os.makedirs(output_dir)

# 爬取图片
getSogouImag('壁纸', 1000, output_dir)

修改的话可以修改getSogouImag中的'壁纸',将其改为其他类型即可爬取相应的图片。

爬取的效果图为:

三、静态图片的爬取

静态图片是指类似网页浏览图片那样,每个页面仅有一张或者几张图片,然后通过点击下一页来获取下一个页面中的图片。这类图片的爬取可以参考[2]。这里[2]给出一个可以直接运行的代码:

# 导入相关的库
import requests
from bs4 import BeautifulSoup
import os

# 待爬取的网址
all_url = 'http://www.mzitu.com'


# http请求头,防止反爬虫
Hostreferer = {
    'User-Agent':'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)',
    'Referer':'http://www.mzitu.com'
               }
# 此请求头破解盗链
Picreferer = {
    'User-Agent':'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)',
    'Referer':'http://i.meizitu.net'
}

# 解析页面
start_html = requests.get(all_url,headers = Hostreferer)

# 爬取图片的保存地址
path = 'D:/mzitu/'

#找寻最大页数
soup = BeautifulSoup(start_html.text,"html.parser")
page = soup.find_all('a',class_='page-numbers')
max_page = page[-2].text


same_url = 'http://www.mzitu.com/page/'
# 逐个爬取套图
for n in range(1,int(max_page)+1):
    ul = same_url+str(n)
    # 解析页面
    start_html = requests.get(ul, headers = Hostreferer)
    soup = BeautifulSoup(start_html.text,"html.parser")
    # 找到图片所在的位置
    all_a = soup.find('div',class_='postlist').find_all('a',target='_blank')
    for a in all_a:
        title = a.get_text()    #提取文本
        if(title != ''):
            print("准备扒取:"+title)

            # win不能创建带?的目录
            if(os.path.exists(path+title.strip().replace('?',''))):
                    #print('目录已存在')
                    flag=1
            else:
                os.makedirs(path+title.strip().replace('?',''))
                flag=0
            os.chdir(path + title.strip().replace('?',''))
            
            # 找到href属性信息
            href = a['href']
            html = requests.get(href,headers = Hostreferer)
            mess = BeautifulSoup(html.text,"html.parser")
            pic_max = mess.find_all('span')
            pic_max = pic_max[9].text          #最大页数
            if(flag == 1 and len(os.listdir(path+title.strip().replace('?',''))) >= int(pic_max)):
                print('已经保存完毕,跳过')
                continue

            # 爬取套图中每一页的图片
            for num in range(1,int(pic_max)+1):
                pic = href+'/'+str(num)
                html = requests.get(pic,headers = Hostreferer)
                mess = BeautifulSoup(html.text,"html.parser")
                pic_url = mess.find('img',alt = title)
                print(pic_url['src'])
                #exit(0)
                html = requests.get(pic_url['src'],headers = Picreferer)
                file_name = pic_url['src'].split(r'/')[-1]
                
                # 保存结果
                f = open(file_name,'wb')
                f.write(html.content)
                f.close()
            print('完成')
    print('第',n,'页完成')

该代码可直接运行,爬取的最终结果就不再展示。

版权声明:本文来源CSDN,感谢博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/z704630835/article/details/82597221
站方申明:本站部分内容来自社区用户分享,若涉及侵权,请联系站方删除。
  • 发表于 2020-03-01 22:40:14
  • 阅读 ( 1272 )
  • 分类:

0 条评论

请先 登录 后评论

官方社群

GO教程

猜你喜欢