• 使用爬虫代码获得深度学习目标检测或者语义分割中的图片。


    问题描述:目标检测或者图像分割需要大量的数据,如果手动从网上找的话会比较慢,这时候,我们可以从网上爬虫下来,然后自己筛选即可。

    代码如下(不要忘记安装代码依赖的库):

    1. # -*- coding: utf-8 -*-
    2. import re
    3. import requests
    4. from urllib import error
    5. from bs4 import BeautifulSoup
    6. import os
    7. num = 0
    8. numPicture = 0
    9. file = ''
    10. List = []
    11. def Find(url, A):
    12. global List
    13. print('正在检测图片总数,请稍等.....')
    14. t = 0
    15. i = 1
    16. s = 0
    17. while t < 1000:
    18. Url = url + str(t)
    19. try:
    20. # 这里搞了下
    21. Result = A.get(Url, timeout=7, allow_redirects=False)
    22. except BaseException:
    23. t = t + 60
    24. continue
    25. else:
    26. result = Result.text
    27. pic_url = re.findall('"objURL":"(.*?)",', result, re.S) # 先利用正则表达式找到图片url
    28. s += len(pic_url)
    29. if len(pic_url) == 0:
    30. break
    31. else:
    32. List.append(pic_url)
    33. t = t + 60
    34. return s
    35. def recommend(url):
    36. Re = []
    37. try:
    38. html = requests.get(url, allow_redirects=False)
    39. except error.HTTPError as e:
    40. return
    41. else:
    42. html.encoding = 'utf-8'
    43. bsObj = BeautifulSoup(html.text, 'html.parser')
    44. div = bsObj.find('div', id='topRS')
    45. if div is not None:
    46. listA = div.findAll('a')
    47. for i in listA:
    48. if i is not None:
    49. Re.append(i.get_text())
    50. return Re
    51. def dowmloadPicture(html, keyword):
    52. global num
    53. # t =0
    54. pic_url = re.findall('"objURL":"(.*?)",', html, re.S) # 先利用正则表达式找到图片url
    55. print('找到关键词:' + keyword + '的图片,即将开始下载图片...')
    56. for each in pic_url:
    57. print('正在下载第' + str(num + 1) + '张图片,图片地址:' + str(each))
    58. try:
    59. if each is not None:
    60. pic = requests.get(each, timeout=7)
    61. else:
    62. continue
    63. except BaseException:
    64. print('错误,当前图片无法下载')
    65. continue
    66. else:
    67. string = file + r'\\' + keyword + '_' + str(num) + '.jpg'
    68. fp = open(string, 'wb')
    69. fp.write(pic.content)
    70. fp.close()
    71. num += 1
    72. if num >= numPicture:
    73. return
    74. if __name__ == '__main__': # 主函数入口
    75. ##############################
    76. # 这里加了点
    77. headers = {
    78. 'Accept-Language': 'zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2',
    79. 'Connection': 'keep-alive',
    80. 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:60.0) Gecko/20100101 Firefox/60.0',
    81. 'Upgrade-Insecure-Requests': '1'
    82. }
    83. A = requests.Session()
    84. A.headers = headers
    85. ###############################
    86. word = input("请输入搜索关键词(可以是人名,地名等): ")
    87. # add = 'http://image.baidu.com/search/flip?tn=baiduimage&ie=utf-8&word=%E5%BC%A0%E5%A4%A9%E7%88%B1&pn=120'
    88. url = 'https://image.baidu.com/search/flip?tn=baiduimage&ie=utf-8&word=' + word + '&pn='
    89. # 这里搞了下
    90. tot = Find(url, A)
    91. Recommend = recommend(url) # 记录相关推荐
    92. print('经过检测%s类图片共有%d张' % (word, tot))
    93. numPicture = int(input('请输入想要下载的图片数量 '))
    94. file = input('请建立一个存储图片的文件夹,输入文件夹名称即可')
    95. y = os.path.exists(file)
    96. if y == 1:
    97. print('该文件已存在,请重新输入')
    98. file = input('请建立一个存储图片的文件夹,)输入文件夹名称即可')
    99. os.mkdir(file)
    100. else:
    101. os.mkdir(file)
    102. t = 0
    103. tmp = url
    104. while t < numPicture:
    105. try:
    106. url = tmp + str(t)
    107. # 这里搞了下
    108. result = A.get(url, timeout=10, allow_redirects=False)
    109. except error.HTTPError as e:
    110. print('网络错误,请调整网络后重试')
    111. t = t + 60
    112. else:
    113. dowmloadPicture(result.text, word)
    114. t = t + 60
    115. print('当前搜索结束,感谢使用')
    116. print('猜你喜欢')
    117. for re in Recommend:
    118. print(re, end=' ')

    这里以搜索明星的图片为例,运行代码,然后根据提示输入搜索图片的名字→搜索图片的张数→保存本地的文件夹即可。

    注意:运行的时候只能使用国内网站,而不能使用外网。不然会出现这个错误→requests.exceptions.SSLError: HTTPSConnectionPool(host='image.baidu.com', port=443): Max retries exceeded with url: /search/flip?tn=baiduimage&ie=utf-8&word=%E6%A1%82%E6%9E%97&pn= (Caused by SSLError(SSLZeroReturnError(6, 'TLS/SSL connection has been closed (EOF) (_ssl.c:1131)')))

  • 相关阅读:
    Vue3记录
    C++ Primer学习笔记-----第十八章:用于大型程序的工具
    氨基修饰/偶联/功能化/接枝二氧化钛,NH2-TiO2,TiO2-NH2
    【List篇】ArrayList 的线程不安全介绍
    SQL Server 中的 ACID 属性
    引用类型复制之后,修改复制的变量不影响原始变量的三种方法
    最新,2022年国自然立项数量统计出炉
    JVM常用参数
    高频笔试题(蔚来)
    SSM+甘肃旅游系统 毕业设计-附源码211707
  • 原文地址:https://blog.csdn.net/weixin_43501408/article/details/132593039