import time
def get_page ( str ) :
print ( "正在下载:" , str )
time. sleep( 2 )
print ( "下载成功:" , str )
name_list= [ 'xiaozi' , 'aa' , 'bb' , 'cc' ]
start_time= time. time( )
for i in range ( len ( name_list) ) :
get_page( name_list[ i] )
end_time= time. time( )
print ( '%d second' % ( end_time- start_time) )
import time
from multiprocessing. dummy import Pool
start_time= time. time( )
def get_page ( str ) :
print ( "正在下载:" , str )
time. sleep( 2 )
print ( "下载成功:" , str )
name_list= [ 'xiaozi' , 'aa' , 'bb' , 'cc' ]
pool= Pool( 4 )
pool. map ( get_page, name_list)
end_time= time. time( )
print ( end_time- start_time)
高性能异步爬虫:
目的:在爬虫中使用异步实现高性能的数据爬取操作
异步爬虫的方式:
- 1.多线程,多进程(不建议)
- 好处:可以为相关阻塞的操作单独开启线程或进程,阻塞操作就可以异步执行
- 弊端:无法无限制开启多线程或多进程
- 2.线程池、进程池:
- 好处:我们可以降低系统对进程或线程创建和销毁的一个频率,从而很好的降低系统的开销。
- 弊端:池中线程或进程的数量是有上线的
- 3.单线程+异步携程(推荐)
evebt_loop:事件循环,相当于一个无限循环,我们可以把一些函数注册到这个时间循环上,
当满足某些条件的时候,函数就会被循环执行。
coroutine:协程对象,我们可以将协程对象注册到事件循环中,它会被事件循环调用。
我们可以使用async关键字定义一个方法,这个方法在调用时不会被立即执行,而是返回
一个协程对象。
task:任务,它是对协程对象进一步进行封装,包含了任务的各个状态。
future:代表将来执行或还没有执行的任务,实际上和task没有本质区别
async:定义一个协程
await:用来挂起阻塞方法的执行
#get方法是一个阻塞的方法
import asyncio
async def request ( url) :
print ( "正在请求的url是:" , url)
print ( "请求成功" , url)
c= request( 'www.baidu.com' )
loop= asyncio. get_event_loop( )
loop. run_until_complete( c)
import asyncio
async def request ( url) :
print ( "正在请求的url是:" , url)
print ( "请求成功" , url)
c= request( 'www.baidu.com' )
loop= asyncio. get_event_loop( )
task= loop. create_task( c)
print ( task)
loop. run_until_complete( task)
print ( task)
import asyncio
async def request ( url) :
print ( "正在请求的url是:" , url)
print ( "请求成功" , url)
c= request( 'www.baidu.com' )
loop= asyncio. get_event_loop( )
task= asyncio. ensure_future( c)
print ( task)
loop. run_until_complete( task)
print ( task)
import asyncio
async def request ( url) :
print ( "正在请求的url是:" , url)
print ( "请求成功" , url)
c= request( 'www.baidu.com' )
def callback_func ( task) :
print ( task. result( ) )
loop= asyncio. get_event_loop( )
task= asyncio. ensure_future( c)
task. add_done_callback( callback_func)
loop. run_until_complete( task)
import asyncio
import time
def request ( url) :
print ( "正在下载" , url)
time. sleep( 2 )
print ( "下载完毕" , url)
start = time. time( )
urls= [
"www.baidu.com" ,
"www.sogou.com" ,
"www.douban.com"
]
stacks= [ ]
for url in urls:
c = request( url)
task = asyncio. ensure_future( c)
stacks. append( task)
loop = asyncio. get_event_loop( )
loop. run_until_complete( asyncio. wait( stacks) )
print ( time. time( ) - start)