0


Python爬虫 自动爬取图片并保存

一、准备工作

用python来实现对百度图片的爬取并保存,以情绪图片为例,百度搜索可得到下图所示

f12打开源码

在此处可以看到这次我们要爬取的图片的基本信息是在img - scr中

二、代码实现

这次的爬取主要用了如下的第三方库

  1. import re
  2. import time
  3. import requests
  4. from bs4 import BeautifulSoup
  5. import os

简单构思可以分为三个小部分

1.获取网页内容

2.解析网页

3.保存图片至相应位置

下面来看第一部分:获取网页内容

  1. baseurl = 'https://cn.bing.com/images/search?q=%E6%83%85%E7%BB%AA%E5%9B%BE%E7%89%87&qpvt=%e6%83%85%e7%bb%aa%e5%9b%be%e7%89%87&form=IGRE&first=1&cw=418&ch=652&tsc=ImageBasicHover'
  2. head = {
  3. "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.131 Safari/537.36 Edg/92.0.902.67"}
  4. response = requests.get(baseurl, headers=head) # 获取网页信息
  5. html = response.text # 将网页信息转化为text形式

是不是so easy

第二部分解析网页才是大头

来看代码

  1. Img = re.compile(r'img.*src="(.*?)"') # 正则表达式匹配图片
  2. soup = BeautifulSoup(html, "html.parser") # BeautifulSoup解析html
  3. #i = 0 # 计数器初始值
  4. data = [] # 存储图片超链接的列表
  5. for item in soup.find_all('img', src=""): # soup.find_all对网页中的img—src进行迭代
  6. item = str(item) # 转换为str类型
  7. Picture = re.findall(Img, item) # 结合re正则表达式和BeautifulSoup, 仅返回超链接
  8. for b in Picture:
  9. data.append(b)
  10. #i = i + 1
  11. return data[-1]
  12. # print(i)

这里就运用到了BeautifulSoup以及re正则表达式的相关知识,需要有一定的基础哦

下面就是第三部分:保存图片

  1. for m in getdata(
  2. baseurl='https://cn.bing.com/images/search?q=%E6%83%85%E7%BB%AA%E5%9B%BE%E7%89%87&qpvt=%e6%83%85%e7%bb%aa%e5%9b%be%e7%89%87&form=IGRE&first=1&cw=418&ch=652&tsc=ImageBasicHover'):
  3. resp = requests.get(m) #获取网页信息
  4. byte = resp.content # 转化为content二进制
  5. print(os.getcwd()) # os库中输出当前的路径
  6. i = i + 1 # 递增
  7. # img_path = os.path.join(m)
  8. with open("path{}.jpg".format(i), "wb") as f: # 文件写入
  9. f.write(byte)
  10. time.sleep(0.5) # 每隔0.5秒下载一张图片放入D://情绪图片测试
  11. print("第{}张图片爬取成功!".format(i))

各行代码的解释已经给大家写在注释中啦,不明白的地方可以直接私信或评论哦~

下面是完整的代码

  1. import re
  2. import time
  3. import requests
  4. from bs4 import BeautifulSoup
  5. import os
  6. # m = 'https://tse2-mm.cn.bing.net/th/id/OIP-C.uihwmxDdgfK4FlCIXx-3jgHaPc?w=115&h=183&c=7&r=0&o=5&pid=1.7'
  7. '''
  8. resp = requests.get(m)
  9. byte = resp.content
  10. print(os.getcwd())
  11. img_path = os.path.join(m)
  12. '''
  13. def main():
  14. baseurl = 'https://cn.bing.com/images/search?q=%E6%83%85%E7%BB%AA%E5%9B%BE%E7%89%87&qpvt=%e6%83%85%e7%bb%aa%e5%9b%be%e7%89%87&form=IGRE&first=1&cw=418&ch=652&tsc=ImageBasicHover'
  15. datalist = getdata(baseurl)
  16. def getdata(baseurl):
  17. Img = re.compile(r'img.*src="(.*?)"') # 正则表达式匹配图片
  18. datalist = []
  19. head = {
  20. "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.131 Safari/537.36 Edg/92.0.902.67"}
  21. response = requests.get(baseurl, headers=head) # 获取网页信息
  22. html = response.text # 将网页信息转化为text形式
  23. soup = BeautifulSoup(html, "html.parser") # BeautifulSoup解析html
  24. # i = 0 # 计数器初始值
  25. data = [] # 存储图片超链接的列表
  26. for item in soup.find_all('img', src=""): # soup.find_all对网页中的img—src进行迭代
  27. item = str(item) # 转换为str类型
  28. Picture = re.findall(Img, item) # 结合re正则表达式和BeautifulSoup, 仅返回超链接
  29. for b in Picture: # 遍历列表,取最后一次结果
  30. data.append(b)
  31. # i = i + 1
  32. datalist.append(data[-1])
  33. return datalist # 返回一个包含超链接的新列表
  34. # print(i)
  35. '''
  36. with open("img_path.jpg","wb") as f:
  37. f.write(byte)
  38. '''
  39. if __name__ == '__main__':
  40. os.chdir("D://情绪图片测试")
  41. main()
  42. i = 0 # 图片名递增
  43. for m in getdata(
  44. baseurl='https://cn.bing.com/images/search?q=%E6%83%85%E7%BB%AA%E5%9B%BE%E7%89%87&qpvt=%e6%83%85%e7%bb%aa%e5%9b%be%e7%89%87&form=IGRE&first=1&cw=418&ch=652&tsc=ImageBasicHover'):
  45. resp = requests.get(m) #获取网页信息
  46. byte = resp.content # 转化为content二进制
  47. print(os.getcwd()) # os库中输出当前的路径
  48. i = i + 1 # 递增
  49. # img_path = os.path.join(m)
  50. with open("path{}.jpg".format(i), "wb") as f: # 文件写入
  51. f.write(byte)
  52. time.sleep(0.5) # 每隔0.5秒下载一张图片放入D://情绪图片测试
  53. print("第{}张图片爬取成功!".format(i))

最后的运行截图

三、总结

这次仅仅是保存了29张图片,在爬取其他网页的时候,用的方法都是大同小异,最主要还是根据网页的内容灵活变换,观察它的源码。另外有部分网站可能会有反爬措施,爬的时候要注意哦~如果还有不懂的地方,欢迎留言私信


本文转载自: https://blog.csdn.net/m0_60964321/article/details/122269923
版权归原作者 清忖灬 所有, 如有侵权,请联系我们删除。

“Python爬虫 自动爬取图片并保存”的评论:

还没有评论