python如何提升爬虫效率
作者:straightup 发布时间:2021-12-17 22:18:24
标签:python,爬虫,效率
单线程+多任务异步协程
协程
在函数(特殊函数)定义的时候,使用async修饰,函数调用后,内部语句不会立即执行,而是会返回一个协程对象
任务对象
任务对象=高级的协程对象(进一步封装)=特殊的函数
任务对象必须要注册到时间循环对象中
给任务对象绑定回调:爬虫的数据解析中
事件循环
当做是一个装载任务对象的容器
当启动事件循环对象的时候,存储在内的任务对象会异步执行
特殊函数内部不能写不支持异步请求的模块,如time,requests...否则虽然不报错但实现不了异步
time.sleep -- asyncio.sleep
requests -- aiohttp
import asyncio
import time
start_time = time.time()
async def get_request(url):
await asyncio.sleep(2)
print(url,'下载完成!')
urls = [
'www.1.com',
'www.2.com',
]
task_lst = [] # 任务对象列表
for url in urls:
c = get_request(url) # 协程对象
task = asyncio.ensure_future(c) # 任务对象
# task.add_done_callback(...) # 绑定回调
task_lst.append(task)
loop = asyncio.get_event_loop() # 事件循环对象
loop.run_until_complete(asyncio.wait(task_lst)) # 注册,手动挂起
线程池+requests模块
# 线程池
import time
from multiprocessing.dummy import Pool
start_time = time.time()
url_list = [
'www.1.com',
'www.2.com',
'www.3.com',
]
def get_request(url):
print('正在下载...',url)
time.sleep(2)
print('下载完成!',url)
pool = Pool(3)
pool.map(get_request,url_list)
print('总耗时:',time.time()-start_time)
两个方法提升爬虫效率
起一个flask服务端
from flask import Flask
import time
app = Flask(__name__)
@app.route('/bobo')
def index_bobo():
time.sleep(2)
return 'hello bobo!'
@app.route('/jay')
def index_jay():
time.sleep(2)
return 'hello jay!'
@app.route('/tom')
def index_tom():
time.sleep(2)
return 'hello tom!'
if __name__ == '__main__':
app.run(threaded=True)
aiohttp模块+单线程多任务异步协程
import asyncio
import aiohttp
import requests
import time
start = time.time()
async def get_page(url):
# page_text = requests.get(url=url).text
# print(page_text)
# return page_text
async with aiohttp.ClientSession() as s: #生成一个session对象
async with await s.get(url=url) as response:
page_text = await response.text()
print(page_text)
return page_text
urls = [
'http://127.0.0.1:5000/bobo',
'http://127.0.0.1:5000/jay',
'http://127.0.0.1:5000/tom',
]
tasks = []
for url in urls:
c = get_page(url)
task = asyncio.ensure_future(c)
tasks.append(task)
loop = asyncio.get_event_loop()
loop.run_until_complete(asyncio.wait(tasks))
end = time.time()
print(end-start)
# 异步执行!
# hello tom!
# hello bobo!
# hello jay!
# 2.0311079025268555
'''
aiohttp模块实现单线程+多任务异步协程
并用xpath解析数据
'''
import aiohttp
import asyncio
from lxml import etree
import time
start = time.time()
# 特殊函数:请求的发送和数据的捕获
# 注意async with await关键字
async def get_request(url):
async with aiohttp.ClientSession() as s:
async with await s.get(url=url) as response:
page_text = await response.text()
return page_text # 返回页面源码
# 回调函数,解析数据
def parse(task):
page_text = task.result()
tree = etree.HTML(page_text)
msg = tree.xpath('/html/body/ul//text()')
print(msg)
urls = [
'http://127.0.0.1:5000/bobo',
'http://127.0.0.1:5000/jay',
'http://127.0.0.1:5000/tom',
]
tasks = []
for url in urls:
c = get_request(url)
task = asyncio.ensure_future(c)
task.add_done_callback(parse) #绑定回调函数!
tasks.append(task)
loop = asyncio.get_event_loop()
loop.run_until_complete(asyncio.wait(tasks))
end = time.time()
print(end-start)
requests模块+线程池
import time
import requests
from multiprocessing.dummy import Pool
start = time.time()
urls = [
'http://127.0.0.1:5000/bobo',
'http://127.0.0.1:5000/jay',
'http://127.0.0.1:5000/tom',
]
def get_request(url):
page_text = requests.get(url=url).text
print(page_text)
return page_text
pool = Pool(3)
pool.map(get_request, urls)
end = time.time()
print('总耗时:', end-start)
# 实现异步请求
# hello jay!
# hello bobo!
# hello tom!
# 总耗时: 2.0467123985290527
小结
爬虫的加速目前掌握了两种方法:
aiohttp模块+单线程多任务异步协程
requests模块+线程池
爬虫接触的模块有三个:
requests
urllib
aiohttp
接触了一下flask开启服务器
来源:https://www.cnblogs.com/straightup/p/13676391.html
0
投稿
猜你喜欢
- DATE_FORMA T(date, format) 根据格式串format 格式化日期或日期和时间值date,返回结果串。可用DATE_F
- 大概在九九年做游戏网站的时候,就对文章的发布感到麻烦,不过那会儿玩ASP不精。只是将就用着。在遇到长文件 10000 字时网页就是一大片长了
- 1.安装第三方模块包pip install django-ckeditor2.添加应用INSTALLED_APPS = [ ..
- 编写一个名为 collatz()的函数,它有一个名为 number 的参数。如果参数是偶数,那么 collatz()就打印出 number
- bookheader.asp Recommended Books for <%=session(&quo
- type 所有类是type生成的a = 1b = "abc"print("type a:{}&qu
- 可能有些地方翻译得不好,请见谅在这个冠冕堂皇的标题之下,我想回答一个土方,有人在博客提出很久了。该土方很好的描述了很多图标设计师所面临的典型
- 配置环境: 1、数 据 库:Oracle 8i R2 (8.1.7) for NT 企业版 2、安装路径:C:ORACLE 实现方法: 1.
- 1、引言小丝:鱼哥, 请教你个问题。小鱼:你觉得你得问题,是正儿八经的吗?小丝:那必须的, 人都正经,何况问题呢?小鱼:那可不敢说, 你得问
- 这是一个网页设计中经常会用到的图片特效,实现多个图片之间的轮换,并分别带有连接。以前的代码只能适用于IE,在FF下始终没有得到很好的解决今天
- 环境:OS:Red Hat Enterprise Linux AS release 4 (Nahant)DB:Oracle Database
- phpinfo() 功能描述:输出 PHP 环境信息以及相关的模块、WEB 环境等信息。 危险等级:中 passthru() 功能描述:允许
- 大家知道,mailto是网页设计制作中的一个非常实用的html标签,许多拥有个人网页的朋友都喜欢在网站的醒目位置处写上自己的电子邮件地址,这
- TEMPLATESDjango 1.8的新特性一个列表,包含所有在Django中使用的模板引擎的设置。列表中的每一项都是一个字典,包含某个引
- 当下,C#与Python都是比较热门的计算机编程语言,他们各有优缺点,如果能让他们互相配合工作,那是多么美好的事情,今天我来讲解一下如何利用
- 今天淘到的,终于可以放心的使用IE7了,再也不用换回IE6做测试了!因为这个10M大小的软件已经包含了从IE3到IE6的版本,安装过程中可以
- 作用:用ASP程序将页面中的电话号码生成图片格式。 代码如下:<% Call Com_CreatValidCode
- 【原文地址】Tip/Trick: Url Rewriting with ASP.NET 【原文发表日期】 Monday, February
- 如何用Cookie进行登录验证?很简单,看看这两个文件:login.htm请注册登录随风起舞<FORM ACTION=&qu
- 在许多情况下,当迁移至SQL Server 2008之前必须了解那些反对和放弃功能的具体情况。下文是几个主要功能在兼容性上的问题列表:1.S