python入门经典(博主录制,免费)

https://study.163.com/course/courseMain.htm?courseId=1006183019&share=2&shareId=400000000398149

两组代码都报错,进行拆分尝试

#! 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() 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.')

  

我写的新代码,都有问题,进行拆分尝试

#! 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 download_single(urlNumber):
print('Downloading page http://xkcd.com/%s...' % (urlNumber))
res = requests.get('http://xkcd.com/%s' % (urlNumber))
res.raise_for_status() soup = bs4.BeautifulSoup(res.text,"lxml") # 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() def downloadXkcd(startComic, endComic):
for urlNumber in range(startComic, endComic):
# Download the page.
try:
download_single(urlNumber)
except:
continue # 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
#i=0,100,200,300
#args=(0,99),(100,199),(200,299).....
downloadThread = threading.Thread(target=downloadXkcd, args=(i, i + 99))
downloadThreads.append(downloadThread) #添加到线程列表
downloadThread.start() # Wait for all threads to end.???
for downloadThread in downloadThreads:
#print("downloadThread:",downloadThread)
downloadThread.join()
print('Done.')

  

For example, calling downloadXkcd(140, 280) would loop over the downloading code to download the comics at http://xkcd.com/140http://xkcd.com/141,http://xkcd.com/142, and so on, up to http://xkcd.com/279. Each thread that you create will call downloadXkcd() and pass a different range of comics to download.

Add the following code to your multidownloadXkcd.py program:

First we make an empy list downloadThreads; the list will help us keep track of the many Thread objects we’ll create. Then we start our for loop. Each time through the loop, we create a Thread object with threading.Thread(), append theThread object to the list, and call start() to start running downloadXkcd() in the new thread. Since the for loop sets the i variable from 0 to 1400 at steps of 100,i will be set to 0 on the first iteration, 100 on the second iteration, 200 on the third, and so on. Since we pass args=(i, i + 99) to threading.Thread(), the two arguments passed to downloadXkcd() will be 0 and 99 on the first iteration, 100and 199 on the second iteration, 200 and 299 on the third, and so on.

As the Thread object’s start() method is called and the new thread begins to run the code inside downloadXkcd(), the main thread will continue to the next iteration of the for loop and create the next thread.

Step 3: Wait for All Threads to End

The main thread moves on as normal while the other threads we create download comics. But say there’s some code you don’t want to run in the main thread until all the threads have completed. Calling a Thread object’s join() method will block until that thread has finished. By using a for loop to iterate over all theThread objects in the downloadThreads list, the main thread can call the join()method on each of the other threads. Add the following to the bottom of your program:

多线程join函数

http://www.jb51.net/article/54628.htm

两个线程开始并发执行,然后执行线程1的join(2),等线程1执行2s后就不管它了,执行线程2的join(2),等线程2执行2s后也不管它了(在此过程中线程1执行结束,打印线程1的结束信息),开始执行主进程,打印「end join」。4s之后线程2执行结束。

总结一下:

1.join方法的作用是阻塞主进程(挡住,无法执行join以后的语句),专注执行多线程。

2.多线程多join的情况下,依次执行各线程的join方法,前头一个结束了才能执行后面一个。

3.无参数,则等待到该线程结束,才开始执行下一个线程的join。

4.设置参数后,则等待该线程这么长时间就不管它了(而该线程并没有结束)。不管的意思就是可以执行后面的主进程了。

最后附上参数为2时的程序执行流程表,自己画的orz,这样看起来更好理解。

https://study.163.com/provider/400000000398149/index.htm?share=2&shareId=400000000398149(博主视频教学主页)

multidownloadXkcd 多线程抓图的更多相关文章

  1. Python爬虫之路——简单网页抓图升级版(添加多线程支持)

    转载自我的博客:http://www.mylonly.com/archives/1418.html 经过两个晚上的奋斗.将上一篇文章介绍的爬虫略微改进了下(Python爬虫之路--简单网页抓图),主要 ...

  2. 多线程(threading)示例

    一.多线程简单示例 import threading,time print('第一线程(默认):程序开始啦!') def takeANap(): time.sleep(5) print('第二线程:5 ...

  3. Python中的多进程与多线程(一)

    一.背景 最近在Azkaban的测试工作中,需要在测试环境下模拟线上的调度场景进行稳定性测试.故而重操python旧业,通过python编写脚本来构造类似线上的调度场景.在脚本编写过程中,碰到这样一个 ...

  4. 多线程爬坑之路-Thread和Runable源码解析之基本方法的运用实例

    前面的文章:多线程爬坑之路-学习多线程需要来了解哪些东西?(concurrent并发包的数据结构和线程池,Locks锁,Atomic原子类) 多线程爬坑之路-Thread和Runable源码解析 前面 ...

  5. 多线程爬坑之路-学习多线程需要来了解哪些东西?(concurrent并发包的数据结构和线程池,Locks锁,Atomic原子类)

    前言:刚学习了一段机器学习,最近需要重构一个java项目,又赶过来看java.大多是线程代码,没办法,那时候总觉得多线程是个很难的部分很少用到,所以一直没下决定去啃,那些年留下的坑,总是得自己跳进去填 ...

  6. Java多线程

    一:进程与线程 概述:几乎任何的操作系统都支持运行多个任务,通常一个任务就是一个程序,而一个程序就是一个进程.当一个进程运行时,内部可能包括多个顺序执行流,每个顺序执行流就是一个线程.   进程:进程 ...

  7. .NET基础拾遗(5)多线程开发基础

    Index : (1)类型语法.内存管理和垃圾回收基础 (2)面向对象的实现和异常的处理基础 (3)字符串.集合与流 (4)委托.事件.反射与特性 (5)多线程开发基础 (6)ADO.NET与数据库开 ...

  8. Java多线程基础——对象及变量并发访问

    在开发多线程程序时,如果每个多线程处理的事情都不一样,每个线程都互不相关,这样开发的过程就非常轻松.但是很多时候,多线程程序是需要同时访问同一个对象,或者变量的.这样,一个对象同时被多个线程访问,会出 ...

  9. C#多线程之线程池篇3

    在上一篇C#多线程之线程池篇2中,我们主要学习了线程池和并行度以及如何实现取消选项的相关知识.在这一篇中,我们主要学习如何使用等待句柄和超时.使用计时器和使用BackgroundWorker组件的相关 ...

随机推荐

  1. 《Linux内核设计与实现》 第三章学习笔记

    一.进程 1.进程就是处于执行期的程序(目标码存放在某种存储介质上).但进程并不仅仅局限于一段可执行程序代码,通常进程还要包含其他资源.执行线程,简称线程(thread),是在进程中活动的对象. 2. ...

  2. IP工具类

    import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.servlet.http.HttpServletReques ...

  3. redis演练

    如何查看所有的key:keys * 如何查询某个key的value:get keyname

  4. QQ的小秘密

    http://ssl.ptlogin2.qq.com/test http://ping.huatuo.qq.com/ http://localhost.ptlogin2.qq.com:4300/mc_ ...

  5. Sqlite,libevent,openssl,mosquito交叉编译

    一.设置交叉编译环境 在makefile所在目录(或源代码根目录)打开终端. 在终端中设置交叉编译所需的临时环境变量(也可写到配置文件中设置为全局环境变量),其中交叉编译工具链的名称和目录需要根据实际 ...

  6. 设计模式之工厂模式(c++)

    问题描述 在面向对象系统设计中经常可以遇到以下的两类问题:1)为了提高内聚(Cohesion)和松耦合(Coupling),我们经常会抽象出一些类的公共接口以形成抽象基类或者接口.这样我们可以通过声明 ...

  7. oracle小知识点

    一 . procedure和function: procedure和function在语法上几乎完全一样,使用上却有小小的差别, procedure可以单独的调用 在命令行直接exec pro_xxx ...

  8. 如何取消浏览器护眼色 Lodop打印图片有窗口颜色的边框

    Lodop打印图片出现了边框,然而通常情况下是没有边框的,由于Lodop是基于本机的ie进行解析的,和IE的设置有关.用户的电脑和习惯千差万别,有人喜欢给浏览器加上护眼色,而这一个行为可能导致Lodo ...

  9. BZOJ2213[Poi2011]Difference——DP

    题目描述 A word consisting of lower-case letters of the English alphabet ('a'-'z') is given. We would li ...

  10. JAVA内部类小结

    内部类的概念:定义在其他类里面的类叫做内部类,包含内部类的类叫做外部类: 内部类的作用:内部类主要是用来描述一个事物存在于另一个事物里面,依赖于外部事物存在的: 内部类的格式: 内部类的分类: 成员内 ...