ITPub博客

首页 > IT职业 > IT图书 > python请求头如何自定义?

python请求头如何自定义?

IT图书 作者:lxhit 时间:2021-09-11 09:57:52 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电脑。

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/4418/viewspace-2830363/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2019-08-12

  • 博文量
    81
  • 访问量
    617