我正在使用以下代码从端点检索 json:
import json
from playwright.sync_api import sync_playwright
API_URL = 'url'
with sync_playwright() as p:
browser = p.webkit.launch(headless=True)
page = browser.new_page()
page.goto(API_URL)
html = page.evaluate('document.querySelector("pre").innerText')
try:
data = json.loads(html)
except:
data = None
print(data)
这适用于 GET 请求,但我应该怎么做才能执行 POST 请求?我正在测试 POST 请求的 url 是API_URL = 'https://www.soraredata.com/api/players/price-graph'
和
POST_data="""
{"player_id": "8244483723335967330548112608338433168438009441877418350246645421695467333117", "scarcity":"Limited", "start_date":"2021-12-21T11:27:04.946521Z", "end_date":"2022-01-21T11:27:04.946521Z", "currency":"Ξ"}
"""
编辑:在hardkoded回答之后,我编辑了我的代码,但仍然无法正常工作(status=403 status_text='Forbidden),即使使用普通浏览器执行的请求似乎是合法的。
import json
from playwright.sync_api import sync_playwright
with sync_playwright() as p:
browser = p.webkit.launch(headless=False)
context = browser.new_context(base_url="https://www.soraredata.com")
api_request_context = context.request
page = context.new_page()
to_send = """
{
"player_id": "8244483723335967330548112608338433168438009441877418350246645421695467333117",
"scarcity":"Limited",
"start_date":"2021-12-26T08:11:09.860Z",
"end_date":"2022-01-25T08:11:08.637Z",
"currency":"Ξ"
}
"""
response = api_request_context.post(
"/api/players/price-graph",
headers={
"Accept": "application/json, text/plain, */*",
"Content-Type": "application/json"
},
data=to_send,
)
try:
print(response)
data = json.loads(response)
except:
# Still might fail sometimes
data = None
print(data)