Python新手求助:如何从curl返回的响应A中获取响应B?
解决方法
基于你现有代码的修改方案
你第一个curl已经把响应内容存在result变量里了,假设这个内容就是你要请求的目标URL,直接把result拼入第二个curl命令即可,记得先清理内容里的换行、空格避免命令出错:
import os # 获取第一个响应(假设内容为目标URL) result = os.popen("curl https://raw.githubusercontent.com/SirdLay/test/main/test.txt").read().strip() # 用拿到的URL发起第二个请求 index = os.popen(f"curl {result}").read()
注意:strip()用于移除字符串首尾的换行符、空格,防止curl命令解析失败。
更推荐的Python原生实现(替代os.popen)
用os.popen执行系统命令并非Python的最佳实践,推荐用内置库或第三方库处理HTTP请求,更安全且易维护:
用requests库(需先执行pip install requests安装)
import requests # 获取第一个响应内容(目标URL) response_a = requests.get("https://raw.githubusercontent.com/SirdLay/test/main/test.txt") target_url = response_a.text.strip() # 请求目标URL得到响应B response_b = requests.get(target_url) index = response_b.text
用Python内置urllib(无需额外安装)
from urllib.request import urlopen # 获取第一个响应内容 with urlopen("https://raw.githubusercontent.com/SirdLay/test/main/test.txt") as resp_a: target_url = resp_a.read().decode('utf-8').strip() # 请求目标URL with urlopen(target_url) as resp_b: index = resp_b.read().decode('utf-8')
内容的提问来源于stack exchange,提问作者Ajesh
相关产品推荐
相关产品推荐

