python_example——14 (python 实现多任务协程下载斗鱼图片)

 # cording = utf-8
import urllib.request
import gevent
from gevent import monkey
import re

monkey.patch_all()


def download(img_png, img_url):
    ret = urllib.request.urlopen(img_url)
    content = ret.read()
    with open(img_png, "wb") as f:
        f.write(content)


def adderress():
    """正则匹配出来的图片"""
    with open("douyu.com_g_yz.html", "r", encoding="utf-8") as f:
        img_url = f.read()

        img_ur2 = re.findall(r"https://[^:]*\.jpg", img_url)
        return img_ur2


def main():
    list1 = adderress()
    n = 1
    list2 = list()  # 定义空列表,保存所有图片下载的协程卵
    for i in list1:
        list2.append(gevent.spawn(download, str(n) + ".jpg", i))
        n += 1
    gevent.joinall(list2)  # joinall 等待所有协程执行完毕


if __name__ == '__main__':
    main()

你可能感兴趣的:(Python_example)