发布于2019-08-06 11:12 阅读(3598) 评论(0) 点赞(2) 收藏(3)
import requests, os, time
import aiohttp, asyncio
import hashlib
class Spider(object):
def __init__(self):
self.headers = {
'User-Agent':''}
self.num = 1
if 'pro' not in os.listdir('.'):
os.mkdir('pro')
self.path = os.path.join(os.path.abspath('.'),'pro')
os.chdir(self.path)# 进入文件下载路径
async def __get_content(self, link): # 传入的是图片链接
async with aiohttp.ClientSession() as session:
response =await session.get(link)
content = await response.read()
return content
def __get_img_links(self, page): # 获取图片链接
# 使用requests请求返回全部图片的链接,也就是一个列表
return 1,2 #
def __get_md5_path_name(self,url_name): # 把图片的URL传入进去,加密得到的字符串来做图片名称
cre_md5 = hashlib.md5()
utf_url_name = url_name.encode(encoding = 'utf-8')
cre_md5.update(utf_url_name)
return cre_md5.hexdigest()
async def __download_img(self, img):
content = await self.__get_content(img) # 获取图片的进制文件
file_name = self.__get_md5_path_name(img) # 获取到MD5名称
with open(file_name + '.jpg', 'wb') as f:
f.write(content)
print('下载第%s张图片成功' % self.num)
self.num +=1
def run(self):
start = time.time()
for x in range(1,101): # 下载一百页的图片就可以了,或者自己更改页数
links = self.__get_img_links(x) # 把那一页需要爬图片的链接传进去
tasks = [asyncio.ensure_future(self.__download_img(link)) for link in links]
loop = asyncio.get_event_loop()
loop.run_until_complete(asyncio.wait(tasks))
if self.num >= 10:# 测试速度使用,如需要下载多张图片可以注释这段代码
break
end = time.time()
print('共运行了%s秒'% (end - start))
def main():
spider = Spider()
spider.run()
if __name__ == '__main__':
main()
作者:老板跑路了
链接:https://www.pythonheidong.com/blog/article/8209/f9dfbd380215fa6df391/
来源:python黑洞网
任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任
昵称:
评论内容:(最多支持255个字符)
---无人问津也好,技不如人也罢,你都要试着安静下来,去做自己该做的事,而不是让内心的烦躁、焦虑,坏掉你本来就不多的热情和定力
Copyright © 2018-2021 python黑洞网 All Rights Reserved 版权所有,并保留所有权利。 京ICP备18063182号-1
投诉与举报,广告合作请联系vgs_info@163.com或QQ3083709327
免责声明:网站文章均由用户上传,仅供读者学习交流使用,禁止用做商业用途。若文章涉及色情,反动,侵权等违法信息,请向我们举报,一经核实我们会立即删除!