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

Python 2.7读取Squarespace托管CSS文件报错,求解决方案

解决Python 2.7读取Squarespace CSS文件时的"unknown url type"错误

Hey there! That "unknown url type" error you're hitting usually happens because either urllib2 struggles with parsing the URL's protocol, or the target resource is redirecting to HTTPS (a scenario urllib2 handles less smoothly than other libraries). Let's walk through two solid fixes to get that CSS file saved locally.

方案1:用Requests库(更简单稳定)

You already imported requests in your code, so let's lean into it—it handles redirects and edge cases way better than raw urllib2. Here's the updated, working code:

import os
import requests

# 目标CSS文件链接
css_url = "http://static.squarespace.com/universal/styles-compressed/audio-player-6c42d60d26f4e09ab1ac335b4bc55b7e-min.css"

try:
    # 发送GET请求,自动处理重定向(比如HTTP转HTTPS)
    response = requests.get(css_url)
    # 检查请求是否成功(抛出异常如果返回4xx/5xx状态码)
    response.raise_for_status()
    
    # 写入本地文件,用二进制模式避免编码问题
    with open("audio-player.css", "wb") as local_file:
        local_file.write(response.content)
    
    print("CSS文件已成功保存到本地!")
except requests.exceptions.RequestException as e:
    # 捕获并打印所有请求相关错误
    print(f"请求过程中出错:{str(e)}")

为什么这个方案更靠谱?

  • requests.get()自动处理HTTP重定向,很多静态资源站点现在强制把HTTP请求转到HTTPS,这正是urllib2容易卡壳的地方。
  • response.raise_for_status()帮你快速排查请求失败原因(比如404找不到文件、500服务器错误)。
  • 用wb模式写入文件,确保CSS内容(哪怕包含特殊字符)能完整正确保存。

方案2:修复Urllib2的用法

If you really need to stick with urllib2, you can tweak your code to handle redirects properly and avoid protocol parsing issues:

import os
import urllib2

css_url = "http://static.squarespace.com/universal/styles-compressed/audio-player-6c42d60d26f4e09ab1ac335b4bc55b7e-min.css"

try:
    # 创建Request对象来处理请求,默认支持重定向
    request = urllib2.Request(css_url)
    response = urllib2.urlopen(request)
    
    # 读取并写入本地文件
    with open("audio-player.css", "wb") as local_file:
        local_file.write(response.read())
    
    print("CSS文件已成功保存到本地!")
except urllib2.URLError as e:
    print(f"请求出错:{str(e)}")

额外小提示

  • 如果遇到403 Forbidden错误,站点可能在检测爬虫,你可以添加一个模拟浏览器的User-Agent头。比如在Requests方案里修改请求部分:
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36"
    }
    response = requests.get(css_url, headers=headers)
    
  • 确保你的Python 2.7环境已经安装了Requests,没装的话用pip install requests安装即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 09:07:58