Python 中的 requests 库将浏览器复制的 cURL 命令转换为请求对象。下面是一个示例:
import requestscurl_command = """curl -X GET \http://example.com/api/data \-H 'Content-Type: application/json' \-H 'Cookie: udid=e9ceb2bb9a6bebb401fcddf5c93ea307; _pbjs_userid_consent_data=35...'"""request = requests.Request(method='GET', url='http://example.com/api/data')# 添加头
for line in curl_command.splitlines():if not line.startswith('  ') and not line.strip().startswith('-H'):continuekey, value = line.lstrip().split(': ', 1)request.headers[key] = valuerequest.prepare_url()print(request.url)  # prints: http://example.com/api/data
print(request.method)  # prints: GET
print(request.headers)  # prints: {'Content-Type': 'application/json', ...}
在这个示例中,我们:
- 将 cURL 命令分割成行。
- 遍历每一行,并提取键值对(例如 -H头)。
- 使用 requests.Request对象的headers属性将这些键值对添加到请求对象中。
- 调用 prepare_url()将请求 URL、方法和其他属性设置好。