社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

如何使用请求库将shell脚本中的curl命令转换为python

Brandon Konieczny • 5 年前 • 1540 次点击  

我正在尝试使用特定的搜索查询从Github API中提取数据并将其放入一个.txt文件中。我可以通过curl和shell来实现这一点,但是我需要用python来实现,我对python非常陌生。我看过请求库

我试过用这个网站 https://curl.trillworks.com/ 使用请求库,但我似乎无法理解如何格式化请求。

curl  -H "Authorization: token xxx" 'https://api.github.com' "https://github.com/api/v3/search/repositories?q=Evidence+locker+Seed+in:readme" > evidencelockerevidence.txt

上面的代码正是我需要它做的事情(传递ghe令牌、调用api、将其存储在一个文件中),我只需要转换成python的帮助。

编辑:解决方案是

import requests

headers = {
    'Authorization': 'token xxx',
}
url = 'https://github.ibm.com/api/v3/search/repositories?q=Evidence+locker+Seed+in:readme'

response = requests.get(url, headers=headers)
print(response)
print(response.text)
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/46270
 
1540 次点击  
文章 [ 1 ]  |  最新文章 5 年前
Caleb Goodman
Reply   •   1 楼
Caleb Goodman    5 年前

全部 -H 标记需要在 headers 钥匙,还有 url 是第一个位置参数。

import requests

headers = {
    'Authorization': 'Bearer bearer_token',
}
url = 'https://github.com/api/v3/search/repositories?q=Evidence+locker+Seed+in:readme'

response = request.get(url, headers=headers)
print(response)
print(response.text)

它处理数据的获取,现在您必须担心将其写入文件,您可以使用 open 内置功能:

with open('path/to/evidencelockerevidence.txt', 'w') as file:
    file.write(response.text)