18.Python爬虫抓取网络照片

本节编写一个快速下载照片的程序,通过百度图片下载您想要的前 60 张图片,并将其保存至相应的目录。本节实战案例是上一节《Python Request库安装和使用》图片下载案例的延伸。

分析url规律

打开百度图片翻页版(点击访问),该翻页版网址要妥善保留。其 url 规律如下:

第一页:https://image.baidu.com/search/flip?tn=baiduimage&word=python&pn=0
第二页:https://image.baidu.com/search/flip?tn=baiduimage&word=python&pn=20
第三页:https://image.baidu.com/search/flip?tn=baiduimage&word=python&pn=40
第n页:https://image.baidu.com/search/flip?tn=baiduimage&word=python&pn=20*(n-1)

百度为了限制爬虫,将原来的翻页版变为了“瀑布流”浏览形式,也就是通过滚动滑轮自动加载图片,此种方式在一定程度上限制了爬虫程序。

写正则表达式

通过上一节可以得知每一张图片有一个源地址如下所示:

data-imgurl="图片源地址"

复制图片源地址,并检查网页源代码,使用 Ctrl+F 搜索该地址,如下图所示:

request模块使用

图1:检查网页结构(点击看高清图


使用上述方式依次检查几张图片,您会发现每张图片源地址,有如下三种匹配结果:

"thumbURL":"https://ss2.bdstatic.com/70cFvnSh_Q1YnxGkpoWK1HF6hhy/it/u=38785274,1357847304&fm=26&gp=0.jpg"
"middleURL":"https://ss2.bdstatic.com/70cFvnSh_Q1YnxGkpoWK1HF6hhy/it/u=38785274,1357847304&fm=26&gp=0.jpg"
"hoverURL":"https://ss2.bdstatic.com/70cFvnSh_Q1YnxGkpoWK1HF6hhy/it/u=38785274,1357847304&fm=26&gp=0.jpg"

任选其一,写出图片源地址正则表达式,如下所示:

re_bds='"hoverURL":"(.*?)"'

编写程序代码

下面使用 Requests 库的相应方法和属性编写程序代码,最终实现一个快速下载照片的小程序。

  1. # -*- coding:utf8 -*-
  2. import requests
  3. import re
  4. from urllib import parse
  5. import os
  6.  
  7. class BaiduImageSpider(object):
  8. def __init__(self):
  9. self.url = 'https://image.baidu.com/search/flip?tn=baiduimage&word={}'
  10. self.headers = {'User-Agent':'Mozilla/4.0'}
  11.  
  12. # 获取图片
  13. def get_image(self,url,word):
  14. #使用 requests模块得到响应对象
  15. res= requests.get(url,headers=self.headers)
  16. # 更改编码格式
  17. res.encoding="utf-8"
  18. # 得到html网页
  19. html=res.text
  20. print(html)
  21. #正则解析
  22. pattern = re.compile('"hoverURL":"(.*?)"',re.S)
  23. img_link_list = pattern.findall(html)
  24. #存储图片的url链接
  25. print(img_link_list)
  26.  
  27. # 创建目录,用于保存图片
  28. directory = 'C:/Users/Administrator/Desktop/image/{}/'.format(word)
  29. # 如果目录不存在则创建,此方法常用
  30. if not os.path.exists(directory):
  31. os.makedirs(directory)
  32.  
  33. #添加计数
  34. i = 1
  35. for img_link in img_link_list:
  36. filename = '{}{}_{}.jpg'.format(directory, word, i)
  37. self.save_image(img_link,filename)
  38. i += 1
  39. #下载图片
  40. def save_image(self,img_link,filename):
  41. html = requests.get(url=img_link,headers=self.headers).content
  42. with open(filename,'wb') as f:
  43. f.write(html)
  44. print(filename,'下载成功')
  45.  
  46. # 入口函数
  47. def run(self):
  48. word = input("您想要谁的照片?")
  49. word_parse = parse.quote(word)
  50. url = self.url.format(word_parse)
  51. self.get_image(url,word)
  52.  
  53. if __name__ == '__main__':
  54. spider = BaiduImageSpider()
  55. spider.run()

程序执行结果如下图:

程序执行结果
图2:程序执行图


目录文件下载图如下所示:

python爬虫实战
图3:程序执行结果
posted @ 2022-08-01 12:57  随遇而安==  阅读(184)  评论(0编辑  收藏  举报