如何通过python发送带有标头的GET请求

我有提琴手来捕获 GET 请求,我想用 python 重新发送确切的请求。这是我捕获的请求:


GET https://example.com/api/content/v1/products/search?page=20&page_size=25&q=&type=image HTTP/1.1

Host: example.com

Connection: keep-alive

Search-Version: v3

Accept: application/json

User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36

Referer: https://example.com/search/?q=&type=image&page=20

Accept-Encoding: gzip, deflate, br

Accept-Language: en-US,en;q=0.9


米琪卡哇伊
浏览 302回答 3
3回答

沧海一幻觉

您可以使用请求模块。该requests模块会自动为您提供大部分标头,因此您很可能不需要手动包含所有标头。由于您正在发送 GET 请求,因此您可以使用该params参数整齐地形成查询字符串。例子:import requestsBASE_URL = "https://example.com/api/content/v1/products/search"headers = {    "Connection": "keep-alive",    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36"}params = {    "page": 20,    "page_size": 25,    "type": "image"}response = requests.get(BASE_URL, headers=headers, params=params)

ibeautiful

import requestsheaders = {    'authority': 'stackoverflow.com',    'cache-control': 'max-age=0',    'upgrade-insecure-requests': '1',    'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36',    'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',    'referer': 'https://stackoverflow.com/questions/tagged/python?sort=newest&page=2&pagesize=15',    'accept-encoding': 'gzip, deflate, br',    'accept-language': 'en-US,en;q=0.9,tr-TR;q=0.8,tr;q=0.7',    'cookie': 'prov=6bb44cc9-dfe4-1b95-a65d-5250b3b4c9fb; _ga=GA1.2.1363624981.1550767314; __qca=P0-1074700243-1550767314392; notice-ctt=4%3B1550784035760; _gid=GA1.2.1415061800.1552935051; acct=t=4CnQ70qSwPMzOe6jigQlAR28TSW%2fMxzx&s=32zlYt1%2b3TBwWVaCHxH%2bl5aDhLjmq4Xr',}response = requests.get('https://stackoverflow.com/questions/55239787/how-to-send-a-get-request-with-headers-via-python', headers=headers)这是如何使用标题向此页面发送获取请求的示例。

一只甜甜圈

您可以打开 SSL 套接字 ( https://docs.python.org/3/library/ssl.html ) example.com:443,将捕获的请求作为原始字节写入此套接字,然后从套接字读取 HTTP 响应。您也可以尝试使用http.client.HTTPResponseclass 来读取和解析来自您的套接字的 HTTP 响应,但不应直接实例化此类,因此可能会出现一些意想不到的障碍。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python