You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 07:30:50