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

WebScraping+FastAPI开发Skyrim API时变量报错、跨文件导入失败问题

Skyrim API 项目修复方案

核心错误点说明

  • Python 无法直接导入文件名包含连字符(-)的模块,sky-scrape.py 中的 - 会被识别为减号运算符,直接导致导入语句报错。
  • 原爬虫代码逻辑存在多处错误:skyrim_data 未提前初始化、html 为未定义变量、数据清洗逻辑写在循环内部导致重复计算、最终输出的数据结构和 FastAPI 接口读取的字典结构不匹配。
  • 原爬虫未加请求头,大概率会被目标网站反爬拦截,返回403错误页面导致解析失败。

修复步骤

  1. 重命名爬虫文件:将sky-scrape.py改名为sky_scrape.py(连字符替换为下划线),和run.py放在同一项目目录下。
  2. 替换sky_scrape.py的全部代码为修正后版本:
from bs4 import BeautifulSoup
import requests
import json

def get_link_data(link):
    # 模拟浏览器请求头,绕过基础反爬
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36"
    }
    resp = requests.get(link, headers=headers)
    resp.raise_for_status()
    return resp.content

# 提前初始化为字典结构,匹配接口读取的键名
skyrim_data = {}
factions_page_content = get_link_data("https://elderscrolls.fandom.com/wiki/Factions_(Skyrim)")
soup = BeautifulSoup(factions_page_content, "html.parser")
wiki_tables = soup.find_all("table", attrs={"class": "wikitable"})

clean_factions = []
for wiki_table in wiki_tables:
    table_body = wiki_table.find("tbody")
    if not table_body:
        continue
    rows = table_body.find_all("tr")
    for row in rows:
        cols = row.find_all("td")
        col_text = [ele.text.strip() for ele in cols]
        valid_row = [item for item in col_text if item]
        if valid_row:
            clean_factions.append(valid_row)

skyrim_data["Factions"] = clean_factions

# 可选:将爬取结果存为本地json,避免每次启动服务都重复爬取
# with open("skyrim_cache.json", "w", encoding="utf-8") as f:
#     json.dump(skyrim_data, f, ensure_ascii=False, indent=2)
  1. 修正run.py的导入语句,完整代码如下:
from fastapi import FastAPI
from fastapi.responses import HTMLResponse
# 从重命名后的模块导入数据
from sky_scrape import skyrim_data

app = FastAPI()

@app.get("/", response_class=HTMLResponse)
def home():
    return """
    <html>
        <head>
            <title>Skyrim API</title>
        </head>
        <body>
            <h1>SKYRIM API</h1>
            <h2>可用路由:</h2>
            <ul>
                <a href="/factions"><li>/factions</li></a>
            </ul>
        </body>
    </html>
    """

@app.get("/factions")
def factions():
    return skyrim_data["Factions"]

运行方式

  • 先安装缺失依赖:
    pip install fastapi uvicorn requests beautifulsoup4
  • 在项目目录下执行启动命令:
    uvicorn run:app --reload
  • 启动后访问http://127.0.0.1:8000即可看到首页,点击路由链接即可查看爬取的阵营数据。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.28 15:57:15