【发布时间】:2022-10-18 21:00:08
【问题描述】:
我对异步编程很陌生,我只是无法从函数中获取 json 数据。是否有某种特殊的方法可以从异步函数传递数据?我想使用 json 数据来提取其他数据。
async def main():
async with async_playwright() as p:
async def handle_response(response):
# the endpoint we are insterested in
if ('eindpoint/name' in response.url):
json_data = await response.json()
print((json_data))
browser = await p.chromium.launch()
page = await browser.new_page()
# go to directly to searchpage
await page.goto("website_url", wait_until='networkidle')
page.on('response', handle_response)
await page.fill('input[id=zoeklocatie]', 'search_query')
# Use two enters to first make button visible
await page.keyboard.press("Enter")
await page.keyboard.press("Enter")
await page.wait_for_timeout(3000)
await browser.close()
await main()
现在的结果是打印了 JSON 数据。但是我怎样才能在函数之外获取这个 JSON 数据并将其进一步用于其他东西。
我试图返回数据和变量。使用全局变量。但是返回值一直是空的,我认为这与代码的异步工作有关。所以回报比结果来得早。
任何人都知道我是否正确以及如何解决这个问题?
谢谢您的帮助!
【问题讨论】:
标签: python async-await playwright