python requests与aiohttp的小对比

最近试着爬小说...突然发现用requests效率不尽人意,查阅了一番,发现了还有aiohttp的存在,不过需要3.5.3以上的版本才能装...

看了下写的demo,10+MB的小说爬取内容仅需大约30s。在本地试了下代码...发现那个网站已经没了...自己试了下效率的确比差很多,但是远不及那个demo中30s爬取百万字数...

大致代码如下...也不是很熟悉,可能有点问题- -

# -*- coding: utf-8 -*-
import requests
import asyncio
import aiohttp
import time
from bs4 import BeautifulSoup

header = {'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:34.0) Gecko/20100101 Firefox/34.0'}
base_url = 'http://www.xbiquge.la'
test_url = 'http://www.xbiquge.la/13/13959/'

def test_1():
    res = requests.get( test_url,headers = header )
    res.encoding = 'utf8'
    text = res.text
    soup = BeautifulSoup(text,'lxml')
    dd_list = soup.find_all('dd')
    for dd in dd_list[:100]:
        url = dd.find('a').get('href')
        res = requests.get( base_url+url,headers=header )

    
           
async def test_2():
    async with aiohttp.ClientSession() as session:
        async with session.get(test_url,headers=header) as res:
            res.encoding = 'utf8'
            text = await res.text()
            soup = BeautifulSoup(text,'lxml')
            dd_list = soup.find_all('dd')
            for dd in dd_list[:100]:
                url = dd.find('a').get('href')
                res = await session.get( base_url+url,headers=header )
               
       
        
        
        
if __name__ == '__main__':
    start = time.time()
    test_1()
    end = time.time()
    print('requests所需时间', end - start )
    start1 = time.time()
    loop = asyncio.get_event_loop()
    loop.run_until_complete(  test_2()  ) 
    end1 = time.time()
    print('aiohttp所需时间', end1 - start1 )

10个章节的所需时间

requests所需时间 5.313061952590942
aiohttp所需时间 3.9156949520111084

50个章节的所需时间

requests所需时间 22.11073350906372
aiohttp所需时间 11.036090612411499

80个章节的所需时间

requests所需时间 37.615445375442505
aiohttp所需时间 19.95256543159485

100个章节的所需时间

requests所需时间 48.59591746330261
aiohttp所需时间 25.8391056060791

 

这结果貌似跟我想象的和之前测别的的结果有点偏差...不过效率的差距很明显。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值