python-异步爬虫(1)

import requests
import logging
import time

logging.basicConfig(level=logging.INFO,format='%(asctime)s-%(levelname)s:%(message)s')

TOTAL_NUMBER=100
URL='https://www.httpbin.org/delay/5'
start_time=time.time()
for i in range(1,TOTAL_NUMBER+1):
    logging.info('scraping%s',URL)
    response=requests.get(URL)
end_time=time.time()
logging.info('total time%s seconds',end_time-start_time)

上面是request遍历程序 直接遍历100遍

下面定义一个协程

import asyncio

async def execute(x):
    print('Number:',x)

coroutine=execute(1)
print('Coroutine:',coroutine)
print('After calling execute')

loop=asyncio.get_event_loop()
loop.run_until_complete(coroutine)
print('After calling loop')

结果

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Python可以使用多种库和框架来实现异步爬虫,其中最常用的是`asyncio`和`aiohttp`。 首先,你需要确保你的Python版本是3.5或更高版本,因为异步编程在这些版本中得到了很好的支持。 接下来,你可以使用`asyncio`库来创建异步任务。异步任务是使用协程(coroutine)定义的,通过使用`async`关键字来声明一个协程函数。在协程函数中,你可以使用`await`关键字来等待其他的异步任务完成。 以下是一个基本的异步爬虫的示例: ```python import asyncio import aiohttp async def fetch(session, url): async with session.get(url) as response: return await response.text() async def main(): async with aiohttp.ClientSession() as session: url = 'https://example.com' html = await fetch(session, url) print(html) loop = asyncio.get_event_loop() loop.run_until_complete(main()) ``` 在这个示例中,我们定义了一个`fetch`函数来发送HTTP请求并返回响应内容。然后,在`main`函数中,我们创建了一个`ClientSession`对象来处理HTTP请求,并且使用`fetch`函数来获取网页内容。最后,我们使用`asyncio.get_event_loop()`来获取事件循环,并调用`run_until_complete()`方法来运行主函数。 这只是一个简单的例子,你可以根据你的需求对其进行扩展和定制。还有其他的库和方法可以用来实现异步爬虫,例如`scrapy`框架、`httpx`库等,你可以根据自己的需求选择合适的工具。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值