程序员文章、书籍推荐和程序员创业信息与资源分享平台

网站首页 > 技术文章 正文

如何用python的requests来下载网页内容保存到txt

hfteth 2025-05-03 14:17:40 技术文章 10 ℃

如何用python的requests来下载网页内容保存到txt

import requests

# 定义目标网页和保存路径
url = "http://www.5a8.com"
filename = "www5a8com.txt"

try:
    # 发送 HTTP GET 请求
    response = requests.get(url, timeout=10)
    response.raise_for_status()  # 检查请求是否成功

    # 自动检测编码并设置,避免乱码
    response.encoding = response.apparent_encoding

    # 写入文件
    with open(filename, "w", encoding="utf-8") as f:
        f.write(response.text)
    print(f"网页内容已保存至 {filename}")

except requests.exceptions.RequestException as e:
    print(f"下载失败: {e}")

运行程序

D:\code\python\get>python geturl.py
网页内容已保存至 www5a8com.txt
最近发表
标签列表