Python的LIB使用aiohttp
问题描述:
有人知道如何做美丽的汤:Python的LIB使用aiohttp
import html5lib
import urllib
from bs4 import BeautifulSoup
soup = BeautifulSoup(urllib.request.urlopen('http://someWebSite.com').read().decode('utf-8'), 'html5lib')
使用urllib模块aiohttp呢?
谢谢^^
答
你可以做这样的事情:
import asyncio
import aiohttp
import html5lib
from bs4 import BeautifulSoup
SELECTED_URL = 'http://someWebSite.com'
async def get_site_content():
async with aiohttp.ClientSession() as session:
async with session.get(SELECTED_URL) as resp:
text = await resp.read()
return BeautifulSoup(text.decode('utf-8'), 'html5lib')
loop = asyncio.get_event_loop()
sites_soup = loop.run_until_complete(get_site_content())
print(sites_soup)
loop.close()
+0
它完美的工作!非常感谢 ;) – APianist
我很好奇,为什么你想这样做。 –
因为urllib阻塞。我需要一个非阻塞的图书馆 – APianist
我无法提供有关您的问题的直接建议。但是,我知道阻塞也可能会在超时时出现。你可能会对这个页面感兴趣:http://docs.python-requests.org/en/latest/user/advanced/#asynchronous-requests('Blocking or Non-Blocking?'and'Timeouts') –