首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >python 多线程下载 脚本

python 多线程下载 脚本

作者头像
用户5760343
发布2022-05-13 18:00:37
发布2022-05-13 18:00:37
5900
举报
文章被收录于专栏:sktjsktj

! python3

multidownloadXkcd.py - Downloads XKCD comics using multiple threads.

import requests, os, bs4, threading os.makedirs('xkcd', exist_ok=True) # store comics in ./xkcd

def downloadXkcd(startComic, endComic): for urlNumber in range(startComic, endComic): # Download the page. print('Downloading page http://xkcd.com/%s...' % (urlNumber)) res = requests.get('http://xkcd.com/%s' % (urlNumber)) res.raise_for_status()

代码语言:javascript
复制
    soup = bs4.BeautifulSoup(res.text)

    # Find the URL of the comic image.
    comicElem = soup.select('#comic img')
    if comicElem == []:
        print('Could not find comic image.')
    else:
        comicUrl = comicElem[0].get('src')
        # Download the image.
        print('Downloading image %s...' % (comicUrl))
        res = requests.get(comicUrl)
        res.raise_for_status()

        # Save the image to ./xkcd
        imageFile = open(os.path.join('xkcd', os.path.basename(comicUrl)), 'wb')
        for chunk in res.iter_content(100000):
            imageFile.write(chunk)
        imageFile.close()

Create and start the Thread objects.

downloadThreads = [] # a list of all the Thread objects for i in range(0, 1400, 100): # loops 14 times, creates 14 threads downloadThread = threading.Thread(target=downloadXkcd, args=(i, i + 99)) downloadThreads.append(downloadThread) downloadThread.start()

Wait for all threads to end.

for downloadThread in downloadThreads: downloadThread.join() print('Done.')

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2022-05-13,如有侵权请联系 cloudcommunity@tencent.com 删除
目录
  • ! python3
  • multidownloadXkcd.py - Downloads XKCD comics using multiple threads.
  • Create and start the Thread objects.
  • Wait for all threads to end.
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档