Python GET请求在Postman中正常,但生成的Python代码不工作

0 投票
1 回答
44 浏览
提问于 2025-04-12 08:03

我有一个在Postman上能正常工作的URL,它能返回数据:

https://www.tablebuilder.singstat.gov.sg/api/table/resourceid?isTestApi=true&keyword=manufacturing&searchoption=all

但是在Postman生成的Python代码却不能正常运行。

import requests
url = "https://www.tablebuilder.singstat.gov.sg/api/table/resourceid?isTestApi=true&keyword=manufacturing&searchoption=all"
response = requests.request("GET", url)
print(response.text)

这可能是什么原因呢?这个代码以前是能正常工作的。有没有什么办法可以永久解决这个问题?

1 个回答

3

你需要提供一个用户代理(User-Agent)HTTP头信息。

比如说:

import requests
import json

url = "https://www.tablebuilder.singstat.gov.sg/api/table/resourceid"
params = {
    "isTestApi": "true",
    "keyword": "manufacturing",
    "searchoption": "all"
}
headers = {
    "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 14_4_1) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.3.1 Safari/605.1.15"
}

with requests.get(url, params=params, headers=headers) as response:
    response.raise_for_status()
    print(json.dumps(response.json(), indent=2))

撰写回答