当我等待页面上进行的 API 调用的响应时,PlayWright 永远不会收到响应。我在多次尝试等待不同页面上的响应时看到过这种情况,但这里有一些示例代码,可以将其范围缩小到我希望的易于复制的情况。
代码超时
from playwright.sync_api import Page
from playwright.sync_api import sync_playwright
import json
with sync_playwright() as p:
browser = p.chromium.launch(headless=False)
page = browser.new_page()
# Goto playwright homepage and press search box:
page.goto("https://playwright.dev/")
page.get_by_role('button', name='Search').click()
# Catching response associated with filling searchfield:
with page.expect_response("**.algolia.net/**") as response:
# Fill a letter in searchbox to trigger the post-request:
page.get_by_placeholder('Search docs').fill('A')
# Printing the value of the response as a python json object:
print(response.value.json())
# Printing the value of the response as raw json:
print(json.dumps(response.value.json()))
这是响应超时时出现的错误消息
Exception has occurred: InvalidStateError
invalid state
File "C:\Users\ronwa\Documents\playwright-test\pwright-search.py", line 23, in <module>
print(response.value.json())
^^^^^^^^^^^^^^
playwright._impl._errors.TimeoutError: Timeout 30000ms exceeded while waiting for event "response"
=========================== logs ===========================
waiting for response **.algolia.net/**
============================================================
During handling of the above exception, another exception occurred:
File "C:\Users\ronwa\Documents\playwright-test\pwright-search.py", line 7, in <module>
with sync_playwright() as p:
asyncio.exceptions.InvalidStateError: invalid state
我认为你不能用
**
删除协议,只能删除路径块。尝试提供它:
from playwright.sync_api import sync_playwright
with sync_playwright() as p:
browser = p.chromium.launch()
page = browser.new_page()
page.goto("https://playwright.dev/")
page.get_by_role("button", name="Search").click()
with page.expect_response("https://*.algolia.net/**") as response:
page.get_by_placeholder("Search docs").fill("A")
print(response.value.json())