![](/img/trans.png)
[英]RuntimeWarning: Enable tracemalloc to get the object allocation traceback
[英]RuntimeWarning: Enable tracemalloc to get the object allocation traceback with asyncio.sleep
嘗試使用信號量來控制異步請求以控制對目標主機的請求,但我收到以下錯誤,我認為這意味着我的asycio.sleep()
實際上並未休眠。 我怎樣才能解決這個問題? 我想為每個目標 URL 的請求添加延遲。
錯誤:
RuntimeWarning: coroutine 'sleep' was never awaited
Coroutine created at (most recent call last)
File "sephora_scraper.py", line 71, in <module>
loop.run_until_complete(main())
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/asyncio/base_events.py", line 571, in run_until_complete
self.run_forever()
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/asyncio/base_events.py", line 539, in run_forever
self._run_once()
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/asyncio/base_events.py", line 1767, in _run_once
handle._run()
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/asyncio/events.py", line 88, in _run
self._context.run(self._callback, *self._args)
File "makeup.py", line 26, in get_html
asyncio.sleep(delay)
asyncio.sleep(delay)
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
代碼:
import sys
import time
import asyncio
import aiohttp
async def get_html(semaphore, session, url, delay=6):
await semaphore.acquire()
async with session.get(url) as res:
html = await res.text()
asyncio.sleep(delay)
semaphore.release()
return html
async def main():
categories = {
"makeup": "https://www.sephora.com/shop/"
}
semaphore = asyncio.Semaphore(value=1)
tasks = []
async with aiohttp.ClientSession(loop=loop, connector=aiohttp.TCPConnector(ssl=False)) as session:
for category, url in categories.items():
# Get HTML of all pages
tasks.append(get_html(semaphore, session, url))
res = await asyncio.gather(*tasks)
if __name__ == "__main__":
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.