打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
用python爬取图片的一点小结

一、原理小结

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

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

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

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

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

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

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

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

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

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

二、动态图片的爬取

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

  1. # 导入相关的库
  2. import requests
  3. import json
  4. import urllib
  5. import os
  6. # 爬取图片的保存路径
  7. output_dir = "./images/"
  8. # 爬取搜狗搜图的函数
  9. def getSogouImag(category, length, path):
  10. '''
  11. 参数category:指要爬取图片的类型,字符串格式,如:'壁纸'
  12. 参数length:指要爬取多少张,整型
  13. 参数path:存储路径
  14. '''
  15. n = length
  16. cate = category
  17. #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
  18. 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')
  19. jd = json.loads(imgs.text)
  20. jd = jd['all_items']
  21. imgs_url = []
  22. for j in jd:
  23. imgs_url.append(j['pic_url'])
  24. m = 0
  25. for img_url in imgs_url:
  26. print('***** '+str(m)+'.jpg *****'+' Downloading...')
  27. urllib.request.urlretrieve(img_url, path+str(m)+'.jpg')
  28. m = m + 1
  29. print('Download complete!')
  30. # 检查是否存在路径,若不存在,则创建
  31. if not os.path.exists(output_dir):
  32. os.makedirs(output_dir)
  33. # 爬取图片
  34. getSogouImag('壁纸', 1000, output_dir)

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

爬取的效果图为:

三、静态图片的爬取

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

  1. # 导入相关的库
  2. import requests
  3. from bs4 import BeautifulSoup
  4. import os
  5. # 待爬取的网址
  6. all_url = 'http://www.mzitu.com'
  7. # http请求头,防止反爬虫
  8. Hostreferer = {
  9. 'User-Agent':'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)',
  10. 'Referer':'http://www.mzitu.com'
  11. }
  12. # 此请求头破解盗链
  13. Picreferer = {
  14. 'User-Agent':'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)',
  15. 'Referer':'http://i.meizitu.net'
  16. }
  17. # 解析页面
  18. start_html = requests.get(all_url,headers = Hostreferer)
  19. # 爬取图片的保存地址
  20. path = 'D:/mzitu/'
  21. #找寻最大页数
  22. soup = BeautifulSoup(start_html.text,"html.parser")
  23. page = soup.find_all('a',class_='page-numbers')
  24. max_page = page[-2].text
  25. same_url = 'http://www.mzitu.com/page/'
  26. # 逐个爬取套图
  27. for n in range(1,int(max_page)+1):
  28. ul = same_url+str(n)
  29. # 解析页面
  30. start_html = requests.get(ul, headers = Hostreferer)
  31. soup = BeautifulSoup(start_html.text,"html.parser")
  32. # 找到图片所在的位置
  33. all_a = soup.find('div',class_='postlist').find_all('a',target='_blank')
  34. for a in all_a:
  35. title = a.get_text() #提取文本
  36. if(title != ''):
  37. print("准备扒取:"+title)
  38. # win不能创建带?的目录
  39. if(os.path.exists(path+title.strip().replace('?',''))):
  40. #print('目录已存在')
  41. flag=1
  42. else:
  43. os.makedirs(path+title.strip().replace('?',''))
  44. flag=0
  45. os.chdir(path + title.strip().replace('?',''))
  46. # 找到href属性信息
  47. href = a['href']
  48. html = requests.get(href,headers = Hostreferer)
  49. mess = BeautifulSoup(html.text,"html.parser")
  50. pic_max = mess.find_all('span')
  51. pic_max = pic_max[10].text #最大页数
  52. if(flag == 1 and len(os.listdir(path+title.strip().replace('?',''))) >= int(pic_max)):
  53. print('已经保存完毕,跳过')
  54. continue
  55. # 爬取套图中每一页的图片
  56. for num in range(1,int(pic_max)+1):
  57. pic = href+'/'+str(num)
  58. html = requests.get(pic,headers = Hostreferer)
  59. mess = BeautifulSoup(html.text,"html.parser")
  60. pic_url = mess.find('img',alt = title)
  61. print(pic_url['src'])
  62. #exit(0)
  63. html = requests.get(pic_url['src'],headers = Picreferer)
  64. file_name = pic_url['src'].split(r'/')[-1]
  65. # 保存结果
  66. f = open(file_name,'wb')
  67. f.write(html.content)
  68. f.close()
  69. print('完成')
  70. print('第',n,'页完成')

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

本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
Python爬虫实战之获取网页图片案例(附代码)
Python爬虫(二):整站爬虫与Web挖掘
在这个520特别的日子里,分享几个用的上的Python代码
Python爬取网易云音乐辑的图片、专辑名和专辑出版时间
新版必应BingChatAi生成爬虫,爬取一百张小姐姐图片教程
爬虫实践---电影排行榜和图片批量下载
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服