You need to enable JavaScript to run this app. Python调用cURL获取网页内容写入txt仅返回0问题求助
优惠活动
大模型
产品
解决方案
定价
更多

Python调用cURL获取网页内容写入txt仅返回0问题求助

问题原因

os.system() 函数的返回值是执行命令的退出状态码,而非命令的标准输出内容:命令执行成功时返回0,执行失败返回非0值。你调用curl得到的网页内容会直接打印到控制台的标准输出流,并不会赋值给writeOut变量,所以写入文件的只有成功状态码0。

修复方案

方案1:使用subprocess模块捕获curl输出

替换os.system的调用逻辑,用subprocess.check_output获取curl的标准输出内容,同步处理编码避免乱码:

import subprocess
# 其余UI相关代码保持不变
def submit_url():
    url = entryURL.get().strip()
    try:
        # 捕获curl输出,指定编码忽略异常字符
        writeOut = subprocess.check_output(f"curl {url}", shell=True, encoding="utf-8", errors="ignore")
    except subprocess.CalledProcessError as e:
        writeOut = f"请求失败,错误码:{e.returncode}"
    # 用with语法自动管理文件关闭
    with open("1.txt", "w", encoding="utf-8") as file:
        file.write("Code: " + writeOut)

方案2:使用Python原生请求库(更稳定,无需依赖系统curl)

直接用requests库发送请求,不需要调用外部curl命令,兼容性更强:

  1. 先执行安装命令:pip install requests
  2. 修改业务逻辑代码:
import requests
# 其余UI相关代码保持不变
def submit_url():
    url = entryURL.get().strip()
    try:
        # 加超时避免卡死,自定义UA避免被部分网站拦截
        resp = requests.get(url, headers={"User-Agent": "Mozilla/5.0"}, timeout=10)
        resp.encoding = resp.apparent_encoding # 自动识别编码避免乱码
        writeOut = resp.text
    except Exception as e:
        writeOut = f"请求失败:{str(e)}"
    with open("1.txt", "w", encoding="utf-8") as file:
        file.write("Code: " + writeOut)

注意事项

  • 输入的URL需要带http/https前缀,否则请求会失败
  • 写入文件时指定encoding=utf-8可以避免中文乱码问题

内容的提问来源于stack exchange,提问作者xunleqitrazer

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.12 16:09:03