我有以下一段代码,它加载一个页面并在其中跟随一个链接,使用文档中asyncio.gather
推荐的 click 方法:
import asyncio
import pyppeteer
async def main(selector):
browser = await pyppeteer.launch()
page = await browser.newPage()
await page.goto("https://example.org")
result = await asyncio.gather(
page.waitForNavigation(),
page.click(selector),
)
result = next(filter(None, result))
if result and isinstance(result, pyppeteer.network_manager.Response):
print(result.status, result.url)
if __name__ == "__main__":
loop = asyncio.get_event_loop()
loop.run_until_complete(main(selector="a"))
当click
方法确实触发导航事件时,这会产生奇迹:
200 https://www.iana.org/domains/reserved
但我正在尝试编写可以处理任何选择器的通用代码,即使是那些不会导致导航的选择器。如果我将选择器更改为“h1”,我会得到以下超时,因为没有导航等待:
Traceback (most recent call last):
File "stackoverflow.py", line 20, in <module>
loop.run_until_complete(main(selector="h1"))
File "/usr/lib/python3.6/asyncio/base_events.py", line 484, in run_until_complete
return future.result()
File "stackoverflow.py", line 12, in main
page.click(selector),
File "/.../lib/python3.6/site-packages/pyppeteer/page.py", line 938, in waitForNavigation
raise error
pyppeteer.errors.TimeoutError: Navigation Timeout Exceeded: 30000 ms exceeded.
我找不到一种方法来检测click
事件是否会产生额外的请求,以避免Page.waitForNavigation
调用。可能吗?在此先感谢您的时间!