• Python爬虫协程批量下载图片


    1. import aiofiles
    2. import aiohttp
    3. import asyncio
    4. import requests
    5. from lxml import etree
    6. from aiohttp import TCPConnector
    7. class Spider:
    8. def __init__(self, value):
    9. # 起始url
    10. self.start_url = value
    11. # 下载单个图片
    12. @staticmethod
    13. async def download_one(url):
    14. name = url[0].split("/")[-1][:-4]
    15. print("开始下载", url, name)
    16. headers = {
    17. 'Host': 'file.jiutuvip.com',
    18. 'User-Agent': 'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, '
    19. 'like Gecko) Chrome/124.0.0.0 Mobile Safari/537.36',
    20. 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8',
    21. 'Accept-Language': 'zh-CN,zh;q=0.9',
    22. 'Accept-Encoding': 'gzip, deflate, br, zstd',
    23. 'Connection': 'keep-alive',
    24. 'Upgrade-Insecure-Requests': '1',
    25. 'Sec-Fetch-Dest': 'document',
    26. 'Sec-Fetch-Mode': 'navigate',
    27. 'Sec-Fetch-Site': 'none',
    28. 'Sec-Fetch-User': '?1',
    29. 'TE': 'trailers'
    30. }
    31. # 发送网络请求
    32. async with aiohttp.ClientSession(connector=TCPConnector(ssl=False)) as session:
    33. async with session.get(url=url[0], headers=headers) as resp: # 相当于 requests.get(url=url[0], headers=head)
    34. # await resp.text() => resp.text
    35. content = await resp.content.read() # => resp.content
    36. # 写入文件
    37. async with aiofiles.open('./imgs/' + name + '.webp', "wb") as f:
    38. await f.write(content)
    39. print("下载完毕")
    40. # 获取图片的url
    41. async def download(self, href_list):
    42. for href in href_list:
    43. async with aiohttp.ClientSession(connector=TCPConnector(ssl=False)) as session:
    44. async with session.get(url=href) as child_res:
    45. html = await child_res.text()
    46. child_tree = etree.HTML(html)
    47. src = child_tree.xpath("//div[@class='article-body cate-6']/a/img/@src") # 选手图片地址 url 列表
    48. await self.download_one(src)
    49. # 获取图片详情url
    50. async def get_img_url(self, html_url):
    51. async with aiohttp.ClientSession(connector=TCPConnector(ssl=False)) as session:
    52. async with session.get(url=html_url) as resp:
    53. html = await resp.text()
    54. tree = etree.HTML(html)
    55. href_list = tree.xpath("//div[@class='uk-container']/ul/li/a/@href") # 选手详情页 url 列表
    56. print(href_list)
    57. await self.download(href_list)
    58. # 页面总页数
    59. @staticmethod
    60. def get_html_url(url):
    61. page = 2
    62. response = requests.get(url=url)
    63. response.encoding = "utf-8"
    64. tree = etree.HTML(response.text)
    65. total_page = tree.xpath("//*[@class='pages']/a[12]/text()") # 页面总页数
    66. print(total_page)
    67. html_url_list = []
    68. while page <= 4: # int(total_page[0]) # 只取第 2、3、4 页
    69. next_url = f"https://www.yeitu.com/meinv/xinggan/{page}.html"
    70. html_url_list.append(next_url)
    71. page += 1
    72. print(html_url_list)
    73. return html_url_list
    74. async def main(self):
    75. # 拿到每页url列表
    76. html_url_list = self.get_html_url(url=self.start_url) # url列表
    77. tasks = []
    78. for html_url in html_url_list:
    79. t = asyncio.create_task(self.get_img_url(html_url)) # 创建任务
    80. tasks.append(t)
    81. await asyncio.wait(tasks)
    82. if __name__ == '__main__':
    83. url = "https://www.yeitu.com/meinv/xinggan/"
    84. sp = Spider(url)
    85. # loop = asyncio.get_event_loop()
    86. # loop = asyncio.new_event_loop()
    87. # asyncio.set_event_loop(loop)
    88. # loop.run_until_complete(sp.main())
    89. asyncio.run(sp.main())

  • 相关阅读:
    CS224W1.1——图机器学习介绍
    Ubuntu 22报错:PAM unable to dlopen(pam_tally2.so)
    java 实现字典树(Trie)
    【计算机网络笔记】计算机网络体系结构概念
    【电源专题】什么是AC/DC转换器
    大话Stable-Diffusion-Webui-客制化主题(一)
    go 语言的映射(map)
    猿创征文|【Hive】各种join连接用法
    java Lock接口
    13.3.6 LIKE条件语句
  • 原文地址:https://blog.csdn.net/sosemseo/article/details/139448283