应用场景
需要对浏览器某些请求二次开发,完成批量操作等自动开发
使用说明
F12->网络 选中请求,右键复制为curl(bash),然后替换到下面代码curl变量,然后运行生成python代码文章来源:https://www.toymoban.com/news/detail-519695.html
import requests
import json
import re
# curl为浏览器请求右键复制的curl(bash)版本,其他curl暂未测试
def curl_requests():
curl = """
curl 'http://xxx' \
-H 'Accept: application/json, text/plain, */*' \
-H 'Accept-Language: zh-CN,zh;q=0.9' \
-H 'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.0.0 Safari/537.36' \
--data-raw '{"expr":null,"datasourceType":[],"warehouseType":[],"pagination":{"pageNum":1,"pageSize":10,"datasourceType":null,"warehouseType":null,"sort":"desc","sortField":"update_time"}}' \
--compressed \
--insecure """
method = "GET"
payload = None
rows = re.split("[ ]{3,}", curl.strip())
url = re.match("curl \'(.*)\'", rows[0]).groups(0)[0]
header = {}
for row in rows[1:]:
if row.startswith("-H"):
groups = re.match("-H [$]?'([\w-]*): (.*)'", row).groups()
key = groups[0]
value = groups[1]
header[key] = value
if row.startswith("--data-raw"):
payload = re.match("--data-raw '(.*)'", row).groups(0)[0]
if payload is not None:
method = "POST"
print(f"url:{url}\nmethod:{method}\nheaders:{header}\npayload:{payload}\n")
print("generate python requests")
print(f"url='{url}'")
print(f"headers={header}")
print(f"payload={json.dumps(payload)}")
print(f"response = requests.requests('{method}',url,payload,headers)")
注意事项
手动编写的curl未测试是否兼容,主要是格式要保持一致,代码是按照浏览器生成的curl格式解析的文章来源地址https://www.toymoban.com/news/detail-519695.html
到了这里,关于Curl转Python代码 (无需依赖Postman)的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!