总是觉得python爬取数据太慢?这些方法轻松提高爬取性能_小说爬取太慢怎么办

# 步骤五(IO阻塞):接收响应体
text=yield from recv.read()

# 步骤六:执行回调函数
callback(host,text)

# 步骤七:关闭套接字
send.close() #没有recv.close()方法,因为是四次挥手断链接,双向链接的两端,一端发完数据后执行send.close()另外一端就被动地断开

if name == ‘main’:
tasks=[
get_page(‘www.baidu.com’,url=‘/s?wd=美女’,ssl=True),
get_page(‘www.cnblogs.com’,url=‘/’,ssl=True),
]

loop=asyncio.get_event_loop()
loop.run_until_complete(asyncio.wait(tasks))
loop.close()

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

import aiohttp
import asyncio

@asyncio.coroutine
def get_page(url):
print(‘GET:%s’ %url)
response=yield from aiohttp.request(‘GET’,url)

data=yield from response.read()

print(url,data)
response.close()
return 1

tasks=[
get_page(‘https://www.python.org/doc’),
get_page(‘https://www.cnblogs.com/linhaifeng’),
get_page(‘https://www.openstack.org’)
]

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

print(‘=====>’,results) #[1, 1, 1]


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



import requests
import asyncio

@asyncio.coroutine
def get_page(func,*args):
print(‘GET:%s’ %args[0])
loog=asyncio.get_event_loop()
furture=loop.run_in_executor(None,func,*args)
response=yield from furture

print(response.url,len(response.text))
return 1

tasks=[
get_page(requests.get,‘https://www.python.org/doc’),
get_page(requests.get,‘https://www.cnblogs.com/linhaifeng’),
get_page(requests.get,‘https://www.openstack.org’)
]

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

print(‘=====>’,results) #[1, 1, 1]


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



from gevent import monkey;monkey.patch_all()
import gevent
import requests

def get_page(url):
print(‘GET:%s’ %url)
response=requests.get(url)
print(url,len(response.text))
return 1

g1=gevent.spawn(get_page,‘https://www.python.org/doc’)

g2=gevent.spawn(get_page,‘https://www.cnblogs.com/linhaifeng’)

g3=gevent.spawn(get_page,‘https://www.openstack.org’)

gevent.joinall([g1,g2,g3,])

print(g1.value,g2.value,g3.value) #拿到返回值

#协程池
from gevent.pool import Pool
pool=Pool(2)
g1=pool.spawn(get_page,‘https://www.python.org/doc’)
g2=pool.spawn(get_page,‘https://www.cnblogs.com/linhaifeng’)
g3=pool.spawn(get_page,‘https://www.openstack.org’)
gevent.joinall([g1,g2,g3,])
print(g1.value,g2.value,g3.value) #拿到返回值


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



#pip3 install grequests

import grequests

request_list=[
grequests.get(‘https://wwww.xxxx.org/doc1’),
grequests.get(‘https://www.cnblogs.com/linhaifeng’),
grequests.get(‘https://www.openstack.org’)
]

执行并获取响应列表

response_list = grequests.map(request_list)

print(response_list)

执行并获取响应列表(处理异常)

def exception_handler(request, exception):
# print(request,exception)
print(“%s Request failed” %request.url)

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


**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 import getPage,defer
from twisted.internet import reactor

def all_done(arg):
# print(arg)
reactor.stop()

def callback(res):
print(res)
return 1

defer_list=[]
urls=[
‘http://www.baidu.com’,
‘http://www.bing.com’,
‘https://www.python.org’,
]
for url in urls:
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 import reactor
reactor.run()
from twisted.web.client import getPage
import urllib.parse

def one_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)


**8、tornado**



from tornado.httpclient import AsyncHTTPClient
from tornado.httpclient import HTTPRequest
from tornado import ioloop
‘’’
更多Python学习资料以及源码教程资料,可以在群1136201545免费获取
‘’’

def handle_response(response):
“”"
处理返回值内容(需要维护计数器,来停止IO循环),调用 ioloop.IOLoop.current().stop()
:param response:
:return:
“”"
if response.error:
print(“Error:”, response.error)
else:
print(response.body)

def func():
url_list = [
‘http://www.baidu.com’,
‘http://www.bing.com’,
]
for url in url_list:
print(url)
http_client = AsyncHTTPClient()
http_client.fetch(HTTPRequest(url), handle_response)

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

#发现上例在所有任务都完毕后也不能正常结束,为了解决该问题,让我们来加上计数器
from tornado.httpclient import AsyncHTTPClient
from tornado.httpclient import HTTPRequest
from tornado import ioloop
‘’’
更多Python学习资料以及源码教程资料,可以在群1136201545免费获取
‘’’
count=0

def handle_response(response):
“”"
处理返回值内容(需要维护计数器,来停止IO循环),调用 ioloop.IOLoop.current().stop()
:param response:
:return:
“”"
if response.error:
print(“Error:”, response.error)
else:
print(len(response.body))

global count
count-=1 #完成一次回调,计数减1
if count == 0:
    ioloop.IOLoop.current().stop() 

def func():
url_list = [
‘http://www.baidu.com’,
‘http://www.bing.com’,
]

global count
for url in url_list:
    print(url)
    http_client = AsyncHTTPClient()
    http_client.fetch(HTTPRequest(url), handle_response)
    count+=1 #计数加1

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


### 关于Python技术储备


学好 Python 不论是就业还是做副业赚钱都不错,但要学会 Python 还是要有一个学习规划。最后大家分享一份全套的 Python 学习资料,给那些想学习 Python 的小伙伴们一点帮助!


包括:Python激活码+安装包、Python web开发,Python爬虫,Python数据分析,Python自动化测试学习等教程。带你从零基础系统性的学好Python!



> 
> 👉[[[CSDN大礼包:《python安装包&全套学习资料》免费分享]]]( )(**安全链接,放心点击**)
> 
> 
> 


#### 一、Python学习大纲


Python所有方向的技术点做的整理,形成各个领域的知识点汇总,它的用处就在于,你可以按照上面的知识点去找对应的学习资源,保证自己学得较为全面。  
 ![在这里插入图片描述](https://img-blog.csdnimg.cn/71e2166464ed45959e2863dae1cc4835.jpeg#pic_center)


#### 二、Python必备开发工具


![在这里插入图片描述](https://img-blog.csdnimg.cn/e496e6652efd47f5bbe73ad2ee082d4a.png)


#### 三、入门学习视频


![](https://img-blog.csdnimg.cn/img_convert/e0106a2ebc87d23666cd0a4b476be14d.png)


#### 四、实战案例


光学理论是没用的,要学会跟着一起敲,要动手实操,才能将自己的所学运用到实际当中去,这时候可以搞点实战案例来学习。![在这里插入图片描述](https://img-blog.csdnimg.cn/7b7d7e133d984b85a09422c3ccfa7396.png)

文末有福利领取哦~
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

👉**一、Python所有方向的学习路线**

Python所有方向的技术点做的整理,形成各个领域的知识点汇总,它的用处就在于,你可以按照上面的知识点去找对应的学习资源,保证自己学得较为全面。![img](https://img-blog.csdnimg.cn/c67c0f87cf9343879a1278dfb067f802.png)

👉**二、Python必备开发工具**

![img](https://img-blog.csdnimg.cn/757ca3f717df4825b7d90a11cad93bc7.png)  
👉**三、Python视频合集**

观看零基础学习视频,看视频学习是最快捷也是最有效果的方式,跟着视频中老师的思路,从基础到深入,还是很容易入门的。  
![img](https://img-blog.csdnimg.cn/31066dd7f1d245159f21623d9efafa68.png)

👉 **四、实战案例**

光学理论是没用的,要学会跟着一起敲,要动手实操,才能将自己的所学运用到实际当中去,这时候可以搞点实战案例来学习。**(文末领读者福利)**  
![img](https://img-blog.csdnimg.cn/e78afb3dcb8e4da3bae5b6ffb9c07ec7.png)

👉**五、Python练习题**

检查学习结果。  
![img](https://img-blog.csdnimg.cn/280da06969e54cf180f4904270636b8e.png)

👉**六、面试资料**

我们学习Python必然是为了找到高薪的工作,下面这些面试题是来自阿里、腾讯、字节等一线互联网大厂最新的面试资料,并且有阿里大佬给出了权威的解答,刷完这一套面试资料相信大家都能找到满意的工作。  
![img](https://img-blog.csdnimg.cn/a9d7c35e6919437a988883d84dcc5e58.png)

![img](https://img-blog.csdnimg.cn/5db8141418d544d3a8e9da4805b1a3f9.png)

👉因篇幅有限,仅展示部分资料,这份完整版的Python全套学习资料已经上传




**网上学习资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。**

**[需要这份系统化学习资料的朋友,可以戳这里无偿获取](https://bbs.csdn.net/topics/618317507)**

**一个人可以走的很快,但一群人才能走的更远!不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!**
  • 5
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值