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

Python/Gspread技术问题:TTRPG爬取数据入Google Sheet需格式化去空白

解决TTRPG怪物数据爬取后写入Google Sheet的格式化问题

第一步:把非结构化爬取数据转成结构化格式

你遇到的核心问题是爬取到的是带大量冗余换行、空白的文本块,而非可直接拆分的结构化数据,所以strip只能清首尾空白,json/ast因为数据格式不合法无法解析。得先提取字段:

如果爬取的是类似键值对的纯文本,用正则匹配提取:

import re

# 示例原始爬取文本
raw_data = """
怪物名称:哥布林

生命值:20

护甲等级:13
速度:30尺
"""

# 匹配所有"字段:值"格式的内容,自动忽略多余空白和换行
pattern = re.compile(r'([^\n:]+)\s*:\s*([^\n]+)')
matches = pattern.findall(raw_data)
# 转成结构化字典
monster_data = {key.strip(): value.strip() for key, value in matches}

如果爬取的是网页HTML表格,直接用BeautifulSoup解析表格结构,不要提取纯文本:

from bs4 import BeautifulSoup

# 假设已获取网页的soup对象
stats_table = soup.find('table', class_='monster-stats')
rows = stats_table.find_all('tr')
# 转成二维列表,对应Sheet的行和列
monster_data = []
for row in rows:
    cols = row.find_all(['th', 'td'])
    cleaned_cols = [col.get_text(strip=True) for col in cols]
    if cleaned_cols:
        monster_data.append(cleaned_cols)

第二步:按结构化数据拆分写入Google Sheet

不要把整块文本丢进单个单元格,而是把每个字段对应到Sheet的列,每行对应一个怪物(以gspread库为例):

import gspread
from oauth2client.service_account import ServiceAccountCredentials

# 初始化Sheet连接(省略认证配置)
scope = ['https://spreadsheets.google.com/feeds', 'https://www.googleapis.com/auth/drive']
creds = ServiceAccountCredentials.from_json_keyfile_name('你的认证文件.json', scope)
client = gspread.authorize(creds)
sheet = client.open('TTRPG怪物库').sheet1

# 单个怪物的情况:先写表头(如果未初始化),再写数据行
headers = list(monster_data.keys())
if sheet.row_values(1) != headers:
    sheet.insert_row(headers, 1)
sheet.append_row(list(monster_data.values()))

# 多个怪物的二维列表,直接批量写入
# sheet.insert_rows(monster_data, row=2)

第三步:深度清理残留冗余格式

如果还有零散的多余空白/换行,对每个字段做统一清理:

def clean_field(text):
    # 把所有连续空白、换行替换成单个空格,再清首尾
    return re.sub(r'\s+', ' ', text).strip()

# 处理字典
monster_data = {k: clean_field(v) for k, v in monster_data.items()}
# 处理二维列表
monster_data = [[clean_field(col) for col in row] for row in monster_data]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 08:22:40