我对异步编程很陌生,我只是无法从函数中获得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数据的函数之外,并使用它进一步的其他东西。
我试图返回数据和变量。使用全局变量。但是返回值一直是空的,我认为这与代码的异步工作有关。因此,返回比结果更早出现。
谁知道如果我是正确的,我怎么能解决这个问题?
谢谢你的帮助!
因此,在Joran的帮助下,我能够使这段代码工作,tx!
我使用了他的建议,两次使用future来获取main()函数之外的数据。
mainRespPromise = asyncio.Future()
async def main():
async with async_playwright() as p:
myRespPromise = asyncio.Future()
async def handle_response(response):
# the endpoint we are insterested in
if ('eindpoint/name' in response.url):
json_data = await response.json()
# "resolve the promise"
myRespPromise.set_result(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)
print("Made call, now await 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")
result_json = await myRespPromise
print("GOT RESULT:",result_json)
await page.wait_for_timeout(3000)
await browser.close()
mainRespPromise.set_result(result_json)
await main()
json_data = await mainRespPromise
你可以使用Future(就像JS中的Promise)
async def main():
async with async_playwright() as p:
myRespPromise = asyncio.Future()
async def handle_response(response):
# the endpoint we are insterested in
if ('eindpoint/name' in response.url):
json_data = await response.json()
# "resolve the promise"
myRespPromise.set_result(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)
print("Made call, now await response...")
result_json = await myRespPromise
print("GOT RESULT:",result_json)
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()