我正在制作一个 python 网络抓取脚本。我应该使用 asyncio 来完成此操作。因此,对于异步 HTTP 请求,我使用 AioHTTP。
没关系,但是当我尝试制作一个非阻塞应用程序(等待)时,beautifulsoup4将阻止应用程序(因为beautifulsoup4不支持异步)
这就是我尝试过的。
import asyncio, aiohttp
from bs4 import BeautifulSoup
async def extractLinks(html):
soup = BeautifulSoup(html, 'html.parser')
return soup.select(".c-pro-box__title a")
async def getHtml(session, url):
async with session.get(url) as response:
return await response.text()
async def loadPage(url):
async with aiohttp.ClientSession() as session:
html = await getHtml(session, url)
links = await extractLinks(html)
return links
loop = asyncio.get_event_loop()
loop.run_until_complete(loadPage())
Run Code Online (Sandbox Code Playgroud)
将extractLinks()阻止程序流。
那么这是否可以使其成为非阻塞呢?或者除了 beautifulsoup4 之外还有其他库可以尽可能支持异步吗?
让我用一个现实生活中的代码示例来解释我的问题:
message = "hello"
for char in message:
print(char)
Run Code Online (Sandbox Code Playgroud)
这个程序输出是:
h
e
l
l
o
Run Code Online (Sandbox Code Playgroud)
但我想知道角色位置。当我使用str.index()它时变成:
message = "hello"
for char in message:
print(char, message.index(char))
Run Code Online (Sandbox Code Playgroud)
输出:
h 0
e 1
l 2
l 2
o 4
Run Code Online (Sandbox Code Playgroud)
该L位置是2,而不是2和3!迭代此消息时如何获取字符位置?
正如 GoDocs 中提到的,os.Create()在特定路径中创建一个文件。
os.Create("fonts/foo/font.eot")
Run Code Online (Sandbox Code Playgroud)
但是当fonts或foo不存在时,它返回panic: open fonts/foo/font.eot: The system cannot find the path specified.
所以我用来os.MkdirAll()创建嵌套目录。但是这个功能还有很多其他的问题。
path := "fonts/foo/font.eot"
// this line create a directory named (font.eot) !
os.MkdirAll(path, os.ModePerm)
Run Code Online (Sandbox Code Playgroud)
有没有更好的方法在嵌套目录中创建文件?