python 爬虫性能_python爬虫篇之 性能相关

一.背景

爬虫的本质就是一个socket客户端与服务端的通信过程,如果我们有多个url待爬取,采用串行的方式执行,只能等待爬取一个结束后才能继续下一个,效率会非常低。

需要强调的是:串行并不意味着低效,如果串行的都是纯计算的任务,那么cpu的利用率仍然会很高,之所以爬虫程序的串行低效,是因为爬虫程序是明显的IO密集型程序。

二.同步,异步,回调机制

在编写爬虫是,性能的消耗主要在IO请求中,当单进程单线程模式下 请求URL时,必然会引起等待,从而使得请求整体变慢。

1.同步:提交一个任务后就在原地等待任务结束,等到拿到任务的结果后在继续下一行代码,效率低下。

importrequestsdeffetch_async(url):

response=requests.get(url)return response #返回信息:response.text...

url_list= ['http://www.jiemian.com','http://www.bing.com']for url inurl_list:print(fetch_async(url))

1.同步执行

2.简单的解决方案:多线程或多进程

#在服务器端使用多线程(或多进程)。多线程(或多进程)的目的是让每个连接都拥有独立的线程(或进程),这样任何一个连接的阻塞都不会影响其他的连接。

from concurrent.futures importThreadPoolExecutorimportrequestsdeffetch_async(url):

response=requests.get(url)returnresponse

url_list= ['http://www.github.com', 'http://www.bing.com']

pool= ThreadPoolExecutor(5)for url inurl_list:

pool.submit(fetch_async, url)

pool.shutdown(wait=True)

2.多线程执行

from multiprocessing importProcessfrom threading importThreadimportrequestsdefget_page(url):

response=requests.get(url)if response.status_code == 200:returnresponse.textif __name__ == '__main__':

urls=['https://www.baidu.com/','http://www.sina.com.cn/','https://www.python.org']for url inurls:

p=Process(target=get_page,args=(url,))

p.start()#t=Thread(target=get_page,args=(url,))

#t.start()

2.1

该方案的局限性:

#开启多进程或都线程的方式,我们是无法无限制地开启多进程或多线程的:在遇到要同时响应成百上千路的连接请求,则无论多线程还是多进程都会严重占据系统资源,降低系统对外界响应效率,而且线程与进程本身也更容易进入假死状态。

3.改进方案:线程池或进程池+异步调用:提交一个任务后并不会等待任务结束,而是继续下一行代码

#很多程序员可能会考虑使用“线程池”或“连接池”。“线程池”旨在减少创建和销毁线程的频率,其维持一定合理数量的线程,并让空闲的线程重新承担新的执行任务。“连接池”维持连接的缓存池,尽量重用已有的连接、减少创建和关闭连接的频率。这两种技术都可以很好的降低系统开销,都被广泛应用很多大型系统,如websphere、tomcat和各种数据库等。

from concurrent.futures importProcessPoolExecutorimportrequestsimportosdeffetch_async(url):print('%s GET : %s' %(os.getpid(), url))

response=requests.get(url)returnresponsedefcallback(future):

future.result()print('%s parsing' %os.getpid())if __name__ == '__main__':

url_list= ['https://www.baidu.com/','http://www.sina.com.cn/','https://www.python.org']

pool= ProcessPoolExecutor(2)for url inurl_list:

v=pool.submit(fetch_async, url)

v.add_done_callback(callback)

pool.shutdown(wait=True)

异步调用+回调机制

改进后方案其实也存在着问题:

#“线程池”和“连接池”技术也只是在一定程度上缓解了频繁调用IO接口带来的资源占用。而且,所谓“池”始终有其上限,当请求大大超过上限时,“池”构成的系统对外界的响应并不比没有池的时候效果好多少。所以使用“池”必须考虑其面临的响应规模,并根据响应规模调整“池”的大小。

对应上例中的所面临的可能同时出现的上千甚至上万次的客户端请求,“线程池”或“连接池”或许可以缓解部分压力,但是不能解决所有问题。总之,多线程模型可以方便高效的解决小规模的服务请求,但面对大规模的服务请求,多线程模型也会遇到瓶颈,可以用非阻塞接口来尝试解决这个问题。

三.高性能

上述五路哪种解决方案其实没有解决一个性能相关的问题:IO阻塞,无论是多进程还是多线程,在遇到IO阻塞式都会被操作系统强行剥夺走CPU的执行权限,程序的执行效率因此就降低了下来。

解决问题的关键在于,我们自己从应用程序级别检测IO阻塞然后切换到我们自己程序的其他任务让其执行,这样吧我们程序的IO降到最低,我们的程序处于就绪态就会增多,以此来迷惑操作系统,操作系统便以为我们的程序是IO比较少的程序,从而会尽可能多的分配CPU给我们,这就就达到提升程序执行效率的目的。

1、在python3.3之后新增了asyncio模块,可以帮我们检测IO(只能是网络IO),实现应用程序级别的切换

importasyncio

@asyncio.coroutinedeffunc1():print('before...func1......')yield from asyncio.sleep(5)print('end...func1......')

tasks=[func1(), func1()]

loop=asyncio.get_event_loop()

loop.run_until_complete(asyncio.gather(*tasks))

loop.close()

1.asyncio示例

2、但asyncio模块只能发tcp级别的请求,不能发http协议,因此,在我们需要发送http请求的时候,需要我们自定义http报头

#我们爬取一个网页的过程,以https://www.python.org/doc/为例,将关键步骤列举如下#步骤一:向www.python.org这台主机发送tcp三次握手,是IO阻塞操作#步骤二:封装http协议的报头#步骤三:发送http协议的请求包,是IO阻塞操作#步骤四:接收http协议的响应包,是IO阻塞操作

importasyncio

@asyncio.coroutinedef get_page(host,port=80,url='/'):#步骤一(IO阻塞):发起tcp链接,是阻塞操作,因此需要yield from

recv,send=yield fromasyncio.open_connection(host,port)#步骤二:封装http协议的报头,因为asyncio模块只能封装并发送tcp包,因此这一步需要我们自己封装http协议的包

requset_headers="""GET %s HTTP/1.0\r\nHost: %s\r\n\r\n""" %(url, host,)#requset_headers="""POST %s HTTP/1.0\r\nHost: %s\r\n\r\nname=egon&password=123""" % (url, host,)

requset_headers=requset_headers.encode('utf-8')#步骤三(IO阻塞):发送http请求包

send.write(requset_headers)yield fromsend.drain()#步骤四(IO阻塞):接收http协议的响应包

text=yield fromrecv.read()#其他处理

print(host,url,text)

send.close()print('-===>')return 1tasks=[get_page(host='www.python.org',url='/doc'),get_page(host='www.cnblogs.com',url='linhaifeng'),get_page(host='www.openstack.org')]

loop=asyncio.get_event_loop()

results=loop.run_until_complete(asyncio.gather(*tasks))

loop.close()print('=====>',results) #[1, 1, 1]

asyncio+自定义http协议报头

importasyncio

@asyncio.coroutinedef fetch_async(host, url='/'):print(host, url)

reader, writer= yield from asyncio.open_connection(host, 80)

request_header_content= """GET %s HTTP/1.0\r\nHost: %s\r\n\r\n""" %(url, host,)

request_header_content= bytes(request_header_content, encoding='utf-8')

writer.write(request_header_content)yield fromwriter.drain()

text= yield fromreader.read()print(host, url, text)

writer.close()

tasks=[

fetch_async('www.cnblogs.com', '/wupeiqi/'),

fetch_async('dig.chouti.com', '/pic/show?nid=4073644713430508&lid=10273091')

]

loop=asyncio.get_event_loop()

results= loop.run_until_complete(asyncio.gather(*tasks))

loop.close()

简约版

3、自定义http报头多少有点麻烦,于是有了aiohttp模块,专门帮我们封装http报头,然后我们还需要用asyncio检测IO实现切换

importaiohttpimportasyncio

@asyncio.coroutinedeffetch_async(url):print(url)

response= yield from aiohttp.request('GET', url)#data = yield from response.read()

#print(url, data)

print(url, response)

response.close()

tasks= [fetch_async('http://www.google.com/'), fetch_async('http://www.chouti.com/')]

event_loop=asyncio.get_event_loop()

results= event_loop.run_until_complete(asyncio.gather(*tasks))

event_loop.close()

asyncio + aiohttp

4、此外,还可以将requests.get函数传给asyncio,就能够被检测了

importasyncioimportrequests

@asyncio.coroutinedef fetch_async(func,*args):

loop=asyncio.get_event_loop()

future= loop.run_in_executor(None,func,*args)

response= yield fromfutureprint(response.url,response.content)

tasks=[

fetch_async(requests.get,'http://www.jiemian.com'),

fetch_async(requests.get,'http://www.biying.com')

]

loop=asyncio.get_event_loop()

results= loop.run_until_complete(asyncio.gather(*tasks))

loop.close()

asyncio + requests

5、还有之前在协程时介绍的gevent模块

importgeventimportrequestsfrom gevent importmonkey

monkey.patch_all()deffetch_async(method, url, req_kwargs):print(method, url, req_kwargs)

response= requests.request(method=method, url=url, **req_kwargs)print(response.url, response.content)###### 发送请求 #####

gevent.joinall([

gevent.spawn(fetch_async, method='get', url='https://www.python.org/', req_kwargs={}),

gevent.spawn(fetch_async, method='get', url='https://www.yahoo.com/', req_kwargs={}),

gevent.spawn(fetch_async, method='get', url='https://github.com/', req_kwargs={}),

])###### 发送请求(协程池控制最大协程数量) ######from gevent.pool import Pool#pool = Pool(None)#gevent.joinall([#pool.spawn(fetch_async, method='get', url='https://www.python.org/', req_kwargs={}),#pool.spawn(fetch_async, method='get', url='https://www.yahoo.com/', req_kwargs={}),#pool.spawn(fetch_async, method='get', url='https://www.github.com/', req_kwargs={}),#])

gevent + requests

6、封装了gevent+requests模块的grequests模块

importgrequests

request_list=[

grequests.get('http://httpbin.org/delay/1', timeout=0.001),

grequests.get('http://fakedomain/'),

grequests.get('http://httpbin.org/status/500')

]###### 执行并获取响应列表 ######response_list = grequests.map(request_list)#print(response_list)

###### 执行并获取响应列表(处理异常) ######def exception_handler(request, exception):#print(request,exception)#print("Request failed")

#response_list = grequests.map(request_list, exception_handler=exception_handler)#print(response_list)

grequests

7、twisted:是一个网络框架,其中一个功能是发送异步请求,检测IO并自动切换

'''#问题一:error: Microsoft Visual C++ 14.0 is required. Get it with "Microsoft Visual C++ Build Tools": http://landinghub.visualstudio.com/visual-cpp-build-tools

https://www.lfd.uci.edu/~gohlke/pythonlibs/#twisted

pip3 install C:\Users\Administrator\Downloads\Twisted-17.9.0-cp36-cp36m-win_amd64.whl

pip3 install twisted

#问题二:ModuleNotFoundError: No module named 'win32api'

https://sourceforge.net/projects/pywin32/files/pywin32/

#问题三:openssl

pip3 install pyopenssl'''

#twisted基本用法

from twisted.web.client importgetPage,deferfrom twisted.internet importreactordefall_done(arg):#print(arg)

reactor.stop()defcallback(res):print(res)return 1defer_list=[]

urls=['http://www.baidu.com','http://www.bing.com','https://www.python.org',

]for url inurls:

obj=getPage(url.encode('utf=-8'),)

obj.addCallback(callback)

defer_list.append(obj)

defer.DeferredList(defer_list).addBoth(all_done)

reactor.run()#twisted的getPage的详细用法

from twisted.internet importreactorfrom twisted.web.client importgetPageimporturllib.parsedefone_done(arg):print(arg)

reactor.stop()

post_data= urllib.parse.urlencode({'check_data': 'adf'})

post_data= bytes(post_data, encoding='utf8')

headers= {b'Content-Type': b'application/x-www-form-urlencoded'}

response= getPage(bytes('http://dig.chouti.com/login', encoding='utf8'),

method=bytes('POST', encoding='utf8'),

postdata=post_data,

cookies={},

headers=headers)

response.addBoth(one_done)

reactor.run()

twisted

from twisted.web.client importgetPage, deferfrom twisted.internet importreactordefall_done(arg):

reactor.stop()defcallback(contents):print(contents)

deferred_list=[]

url_list= ['http://www.bing.com', 'http://www.baidu.com', ]for url inurl_list:

deferred= getPage(bytes(url, encoding='utf8'))

deferred.addCallback(callback)

deferred_list.append(deferred)

dlist=defer.DeferredList(deferred_list)

dlist.addBoth(all_done)

reactor.run()

简约版

dlist.addBoth(all_done) #无论正确与否,都会执行 回调函数

dlist.addCallback(all_done) #正确的时候,执行

dlist.addErrback(all_done) #错误的时候,执行

执行回调的三种方式

from twisted.web.client importgetPage, deferfrom twisted.internet importreactordefcallback(contents):print(contents)

@defer.inlineCallbacksdeftask(url):#defer.Deferred() -------》返回defer对象

d = getPage(bytes(url, encoding='utf8'))

d.addCallback(callback)yieldd

url_list= ['http://www.bing.com', 'http://www.baidu.com', ]

_active=[]for url inurl_list:

d=task(url)

_active.append(d)defall_done(arg):

reactor.stop()

xx=defer.DeferredList(_active)

xx.addBoth(all_done)

reactor.run()

@defer.inlineCallbacks

8.Tornado

from tornado.httpclient importAsyncHTTPClientfrom tornado.httpclient importHTTPRequestfrom tornado importioloopdefhandle_response(response):"""处理返回值内容(需要维护计数器,来停止IO循环),调用 ioloop.IOLoop.current().stop()

:param response:

:return:"""

ifresponse.error:print("Error:", response.error)else:print(response.body)deffunc():

url_list=['http://www.baidu.com','http://www.bing.com',

]for url inurl_list:print(url)

http_client=AsyncHTTPClient()

http_client.fetch(HTTPRequest(url), handle_response)

ioloop.IOLoop.current().add_callback(func)

ioloop.IOLoop.current().start()

Tornado

from twisted.web.client importgetPage,deferfrom twisted.internet importreactordefall_done(arg):

reactor.stop()defcallback(contents):print(contents)

deferred_list=[]

url_list= ['http://www.jiemian.com', 'http://www.baidu.com',]for url inurl_list:

deferred= getPage(bytes(url,encoding='utf8'))

deferred.addCallback(callback)

deferred_list.append(deferred)

dlist=defer.DeferredList(deferred_list)

dlist.addBoth(all_done)

react8、tornado

以上是Python内置以及第三方提供的异步IO请求模块,使用简便大大提高效率,而对异步IO请求的本质则是 [ 非阻塞Socket ] + [IO多路复用]:

importselectimportsocketimporttimeclassAsyncTimeoutException(TimeoutError):"""请求超时异常类"""

def __init__(self, msg):

self.msg=msg

super(AsyncTimeoutException, self).__init__(msg)classHttpContext(object):"""封装请求和相应的基本数据"""

def __init__(self, sock, host, port, method, url, data, callback, timeout=5):"""sock: 请求的客户端socket对象

host: 请求的主机名

port: 请求的端口

port: 请求的端口

method: 请求方式

url: 请求的URL

data: 请求时请求体中的数据

callback: 请求完成后的回调函数

timeout: 请求的超时时间"""self.sock=sock

self.callback=callback

self.host=host

self.port=port

self.method=method

self.url=url

self.data=data

self.timeout=timeout

self.__start_time =time.time()

self.__buffer =[]defis_timeout(self):"""当前请求是否已经超时"""current_time=time.time()if (self.__start_time + self.timeout)

returnself.sock.fileno()defwrite(self, data):"""在buffer中写入响应内容"""self.__buffer.append(data)def finish(self, exc=None):"""在buffer中写入响应内容完成,执行请求的回调函数"""

if notexc:

response= b''.join(self.__buffer)

self.callback(self, response, exc)else:

self.callback(self, None, exc)defsend_request_data(self):

content= """%s %s HTTP/1.0\r\nHost: %s\r\n\r\n%s""" %(

self.method.upper(), self.url, self.host, self.data,)return content.encode(encoding='utf8')classAsyncRequest(object):def __init__(self):

self.fds=[]

self.connections=[]defadd_request(self, host, port, method, url, data, callback, timeout):"""创建一个要请求"""client=socket.socket()

client.setblocking(False)try:

client.connect((host, port))exceptBlockingIOError as e:pass

#print('已经向远程发送连接的请求')

req =HttpContext(client, host, port, method, url, data, callback, timeout)

self.connections.append(req)

self.fds.append(req)defcheck_conn_timeout(self):"""检查所有的请求,是否有已经连接超时,如果有则终止"""timeout_list=[]for context inself.connections:ifcontext.is_timeout():

timeout_list.append(context)for context intimeout_list:

context.finish(AsyncTimeoutException('请求超时'))

self.fds.remove(context)

self.connections.remove(context)defrunning(self):"""事件循环,用于检测请求的socket是否已经就绪,从而执行相关操作"""

whileTrue:

r, w, e= select.select(self.fds, self.connections, self.fds, 0.05)if notself.fds:return

for context inr:

sock=context.sockwhileTrue:try:

data= sock.recv(8096)if notdata:

self.fds.remove(context)

context.finish()break

else:

context.write(data)exceptBlockingIOError as e:break

exceptTimeoutError as e:

self.fds.remove(context)

self.connections.remove(context)

context.finish(e)break

for context inw:#已经连接成功远程服务器,开始向远程发送请求数据

if context inself.fds:

data=context.send_request_data()

context.sock.sendall(data)

self.connections.remove(context)

self.check_conn_timeout()if __name__ == '__main__':defcallback_func(context, response, ex):""":param context: HttpContext对象,内部封装了请求相关信息

:param response: 请求响应内容

:param ex: 是否出现异常(如果有异常则值为异常对象;否则值为None)

:return:"""

print(context, response, ex)

obj=AsyncRequest()

url_list=[

{'host': 'www.google.com', 'port': 80, 'method': 'GET', 'url': '/', 'data': '', 'timeout': 5,'callback': callback_func},

{'host': 'www.baidu.com', 'port': 80, 'method': 'GET', 'url': '/', 'data': '', 'timeout': 5,'callback': callback_func},

{'host': 'www.bing.com', 'port': 80, 'method': 'GET', 'url': '/', 'data': '', 'timeout': 5,'callback': callback_func},

]for item inurl_list:print(item)

obj.add_request(**item)

obj.running()

武器版的异步IO模块

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值