python请求头如何自定义?

Python (186) 2023-05-04 19:36:41

1、说明

要自定义请求头,可以使用 headers 参数将HTTP头部组成的字典传递给get()。

2、实例

可以通过Accept中指定文本匹配媒体类型来更改以前的搜索请求,以在结果中突出显示匹配的搜索字词:

importrequests

response=requests.get(
'https://api.github.com/search/repositories',
params={'q':'requests+language:python'},
headers={'Accept':'application/vnd.github.v3.text-match+json'},
)

#Viewthenew`text-matches`arraywhichprovidesinformation
#aboutyoursearchtermwithintheresults
json_response=response.json()
repository=json_response['items'][0]
print(f'Textmatches:{repository["text_matches"]}')

Accept 告诉服务器你的应用程序可以处理哪些内容类型。 由于希望突出显示匹配的搜索词,所以使用的是 application / vnd.github.v3.text-match + json,这是一个专有的GitHub的 Accept 标头,其内容为特殊的JSON格式。

以上就是python请求头自定义的方法,希望对大家有所帮助。

本文教程操作环境:windows7系统、Python 3.9.1,DELL G3电脑。

THE END

发表回复