
1、说明
要自定义请求头,可以使用 headers 参数将HTTP头部组成的字典传递给get()。
2、实例
可以通过Accept中指定文本匹配媒体类型来更改以前的搜索请求,以在结果中突出显示匹配的搜索字词:
1 2 3 4 5 6 7 8 9 10 11 12 13 | import requests
response = requests.get(
'https://api.github.com/search/repositories' ,
params={ 'q' : 'requests+language:python' },
headers={ 'Accept' : 'application/vnd.github.v3.text-match+json' },
)
# View the new `text-matches` array which provides information
# about your search term within the results
json_response = response.json()
repository = json_response[ 'items' ][0]
print(f 'Text matches: {repository["text_matches"]}' )
|
Accept 告诉服务器你的应用程序可以处理哪些内容类型。 由于希望突出显示匹配的搜索词,所以使用的是 application / vnd.github.v3.text-match + json,这是一个专有的GitHub的 Accept 标头,其内容为特殊的JSON格式。
以上就是python请求头自定义的方法,希望对大家有所帮助。更多Python学习指路:python基础教程
本文教程操作环境:windows7系统、Python 3.9.1,DELL G3电脑。