品易云推流 关闭
文章详情页
文章 > Python基础教程 > python请求头如何自定义?

python请求头如何自定义?

头像

小妮浅浅

2021-05-31 09:32:563430浏览 · 0收藏 · 0评论

1、说明

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

2、实例

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

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电脑。

关注

关注公众号,随时随地在线学习

本教程部分素材来源于网络,版权问题联系站长!

底部广告图