0

0

我更新了 BoardGameGeek 数据的 Python 获取器

DDD

DDD

发布时间:2024-10-15 22:25:17

|

718人浏览过

|

来源于dev.to

转载

我更新了 boardgamegeek 数据的 python 获取器

此脚本将从 boardgamegeek api 获取项目数据并将数据存储在 csv 文件中。

我更新了之前的脚本。由于 api 响应采用 xml 格式,并且没有端点可以一次获取所有项目,因此前面的脚本将循环遍历提供的 id 范围,对每个项目进行逐一调用。这不是最优的,对于较大范围的 id 来说需要很长时间(目前 bgg 上可用的项目 (id) 的最高数量高达 400k+),并且结果可能不可靠。因此,通过对此脚本的一些修改,更多的项目id将作为参数值添加到单个请求url中,这样,单个响应将返回多个项目(〜800是单个响应返回的最高数量。bgg稍后可能会更改它;您可以轻松调整batch_size以便根据需要进行调整)。

此外,此脚本将获取所有项目,而不仅仅是与棋盘游戏相关的数据。

为每个棋盘游戏获取和存储的信息如下:

立即学习Python免费学习笔记(深入)”;

名称、游戏 id、类型、评级、权重、发布年份、最小玩家数、最大玩家数、最短游戏时间、最大支付时间、最小年龄、所属者、类别、机制、设计师、艺术家和发行商。

网梦购物系统
网梦购物系统

一套功能完善、性能稳定的经典网上购物系统,掌握了一整套从算法,数据结构到产品安全性方面的领先技术,使程序无论在安全性、负载能力方面均获得了成功,新版购物系统集成多种在线支付方式,全后台操作管理,并集成了Ewebedit编辑器,即使只有电脑基础知识的人也能够轻松操作和管理部分新增功能:集成多种网上支付形式,后台灵活切换增加Ewebedit编辑器,添加信息更容易!简洁、明快、新颖的界面,给人以美的感觉

下载

该脚本的更新如下;我们首先导入此脚本所需的库:

# import libraries
from bs4 import beautifulsoup
from csv import dictwriter
import pandas as pd
import requests
import time

以下是脚本完成时根据 id 范围调用的函数。此外,如果发出请求时出现错误,将调用此函数以存储截至异常发生时附加到游戏列表的所有数据。

# csv file saving function
def save_to_csv(games):
    csv_header = [
        'name', 'game_id', 'type', 'rating', 'weight', 'year_published', 'min_players', 'max_players',
        'min_play_time', 'max_play_time', 'min_age', 'owned_by', 'categories',
        'mechanics', 'designers', 'artists', 'publishers'
    ]
    with open('bgg.csv', 'a', encoding='utf8') as f:
        dictwriter_object = dictwriter(f, fieldnames=csv_header)
        if f.tell() == 0:
            dictwriter_object.writeheader()
        dictwriter_object.writerows(games)

我们需要定义请求的标头。请求之间的暂停可以通过 sleep_between_requests 设置(我看到一些信息说速率限制是每秒 2 个请求,但它可能是过时的信息,因为我将暂停设置为 0 没有遇到问题)。另外,这里设置起始点id(start_id_range)、最大范围(max_id_range)和batch_size的值,batch_size是响应应该返回的游戏数量。基本 url 在本节中定义,但 id 在脚本的下一部分中添加。

# define request url headers
headers = {
    "user-agent": "mozilla/5.0 (macintosh; intel mac os x 10.16; rv:85.0) gecko/20100101 firefox/85.0",
    "accept-language": "en-gb, en-us, q=0.9, en"
}

# define sleep timer value between requests
sleep_between_request = 0

# define max id range
start_id_range = 0
max_id_range = 403000
batch_size = 800
base_url = "https://boardgamegeek.com/xmlapi2/thing?id="

下面是这个脚本的主要逻辑。首先,根据批量大小,它会生成一个在定义的 id 范围内的 id 字符串,但 id 的数量不得超过 batch_size 中定义的数量,并将其附加到 url 的 id 参数中。这样,每个响应将返回与批量大小相同的项目数量的数据。之后,它将处理数据并将其附加到每个响应的游戏列表中,最后附加到 csv 文件中。

# main loop that will iterate between the starting and maximum range in intervals of the batch size
for batch_start in range(start_id_range, max_id_range, batch_size):
    # make sure that the batch size will not exceed the maximum ids range
    batch_end = min(batch_start + batch_size - 1, max_id_range)
    # join and append to the url the ids within batch size
    ids = ",".join(map(str, range(batch_start, batch_end + 1)))
    url = f"{base_url}?id={ids}&stats=1"

    # if by any chance there is an error, this will throw the exception and continue on the next batch
    try:
        response = requests.get(url, headers=headers)
    except exception as err:
        print(err)
        continue


    if response.status_code == 200:
        soup = beautifulsoup(response.text, features="html.parser")
        items = soup.find_all("item")
        games = []
        for item in items:
            if item:
                try:
                    # find values in the xml
                    name = item.find("name")['value'] if item.find("name") is not none else 0
                    year_published = item.find("yearpublished")['value'] if item.find("yearpublished") is not none else 0
                    min_players = item.find("minplayers")['value'] if item.find("minplayers") is not none else 0
                    max_players = item.find("maxplayers")['value'] if item.find("maxplayers") is not none else 0
                    min_play_time = item.find("minplaytime")['value'] if item.find("minplaytime") is not none else 0
                    max_play_time = item.find("maxplaytime")['value'] if item.find("maxplaytime") is not none else 0
                    min_age = item.find("minage")['value'] if item.find("minage") is not none else 0
                    rating = item.find("average")['value'] if item.find("average") is not none else 0
                    weight = item.find("averageweight")['value'] if item.find("averageweight") is not none else 0
                    owned = item.find("owned")['value'] if item.find("owned") is not none else 0


                    link_type = {'categories': [], 'mechanics': [], 'designers': [], 'artists': [], 'publishers': []}

                    links = item.find_all("link")

                    # append value(s) for each link type
                    for link in links:                            
                        if link['type'] == "boardgamecategory":
                            link_type['categories'].append(link['value'])
                        if link['type'] == "boardgamemechanic":
                            link_type['mechanics'].append(link['value'])
                        if link['type'] == "boardgamedesigner":
                            link_type['designers'].append(link['value'])
                        if link['type'] == "boardgameartist":
                            link_type['artists'].append(link['value'])
                        if link['type'] == "boardgamepublisher":
                            link_type['publishers'].append(link['value'])

                    # append 0 if there is no value for any link type
                    for key, ltype in link_type.items():
                        if not ltype:
                            ltype.append("0")

                    game = {
                        "name": name,
                        "game_id": item['id'],
                        "type": item['type'],
                        "rating": rating,
                        "weight": weight,
                        "year_published": year_published,
                        "min_players": min_players,
                        "max_players": max_players,
                        "min_play_time": min_play_time,
                        "max_play_time": max_play_time,
                        "min_age": min_age,
                        "owned_by": owned,
                        "categories": ', '.join(link_type['categories']),
                        "mechanics": ', '.join(link_type['mechanics']),
                        "designers": ', '.join(link_type['designers']),
                        "artists": ', '.join(link_type['artists']),
                        "publishers": ', '.join(link_type['publishers']),
                    }

                    # append current item to games list
                    games.append(game)
                except typeerror:
                    print(">>> nonetype error. continued on the next item.")
                    continue
        save_to_csv(games)

        print(f">>> request successful for batch {batch_start}-{batch_end}")
    else:
        print(f">>> failed batch {batch_start}-{batch_end}")

    # pause between requests
    time.sleep(sleep_between_request)

下面您可以以 pandas dataframe 的形式预览 csv 文件中的前几行记录。

# Preview the CSV as pandas DataFrame
df = pd.read_csv('./bgg.csv')
print(df.head(5))

热门AI工具

更多
DeepSeek
DeepSeek

幻方量化公司旗下的开源大模型平台

豆包大模型
豆包大模型

字节跳动自主研发的一系列大型语言模型

通义千问
通义千问

阿里巴巴推出的全能AI助手

腾讯元宝
腾讯元宝

腾讯混元平台推出的AI助手

文心一言
文心一言

文心一言是百度开发的AI聊天机器人,通过对话可以生成各种形式的内容。

讯飞写作
讯飞写作

基于讯飞星火大模型的AI写作工具,可以快速生成新闻稿件、品宣文案、工作总结、心得体会等各种文文稿

即梦AI
即梦AI

一站式AI创作平台,免费AI图片和视频生成。

ChatGPT
ChatGPT

最最强大的AI聊天机器人程序,ChatGPT不单是聊天机器人,还能进行撰写邮件、视频脚本、文案、翻译、代码等任务。

相关专题

更多
Python 时间序列分析与预测
Python 时间序列分析与预测

本专题专注讲解 Python 在时间序列数据处理与预测建模中的实战技巧,涵盖时间索引处理、周期性与趋势分解、平稳性检测、ARIMA/SARIMA 模型构建、预测误差评估,以及基于实际业务场景的时间序列项目实操,帮助学习者掌握从数据预处理到模型预测的完整时序分析能力。

68

2025.12.04

pdf怎么转换成xml格式
pdf怎么转换成xml格式

将 pdf 转换为 xml 的方法:1. 使用在线转换器;2. 使用桌面软件(如 adobe acrobat、itext);3. 使用命令行工具(如 pdftoxml)。本专题为大家提供相关的文章、下载、课程内容,供大家免费下载体验。

1903

2024.04.01

xml怎么变成word
xml怎么变成word

步骤:1. 导入 xml 文件;2. 选择 xml 结构;3. 映射 xml 元素到 word 元素;4. 生成 word 文档。提示:确保 xml 文件结构良好,并预览 word 文档以验证转换是否成功。想了解更多xml的相关内容,可以阅读本专题下面的文章。

2092

2024.08.01

xml是什么格式的文件
xml是什么格式的文件

xml是一种纯文本格式的文件。xml指的是可扩展标记语言,标准通用标记语言的子集,是一种用于标记电子文件使其具有结构性的标记语言。想了解更多相关的内容,可阅读本专题下面的相关文章。

1081

2024.11.28

js 字符串转数组
js 字符串转数组

js字符串转数组的方法:1、使用“split()”方法;2、使用“Array.from()”方法;3、使用for循环遍历;4、使用“Array.split()”方法。本专题为大家提供js字符串转数组的相关的文章、下载、课程内容,供大家免费下载体验。

320

2023.08.03

js截取字符串的方法
js截取字符串的方法

js截取字符串的方法有substring()方法、substr()方法、slice()方法、split()方法和slice()方法。本专题为大家提供字符串相关的文章、下载、课程内容,供大家免费下载体验。

212

2023.09.04

java基础知识汇总
java基础知识汇总

java基础知识有Java的历史和特点、Java的开发环境、Java的基本数据类型、变量和常量、运算符和表达式、控制语句、数组和字符串等等知识点。想要知道更多关于java基础知识的朋友,请阅读本专题下面的的有关文章,欢迎大家来php中文网学习。

1502

2023.10.24

字符串介绍
字符串介绍

字符串是一种数据类型,它可以是任何文本,包括字母、数字、符号等。字符串可以由不同的字符组成,例如空格、标点符号、数字等。在编程中,字符串通常用引号括起来,如单引号、双引号或反引号。想了解更多字符串的相关内容,可以阅读本专题下面的文章。

624

2023.11.24

C++ 设计模式与软件架构
C++ 设计模式与软件架构

本专题深入讲解 C++ 中的常见设计模式与架构优化,包括单例模式、工厂模式、观察者模式、策略模式、命令模式等,结合实际案例展示如何在 C++ 项目中应用这些模式提升代码可维护性与扩展性。通过案例分析,帮助开发者掌握 如何运用设计模式构建高质量的软件架构,提升系统的灵活性与可扩展性。

14

2026.01.30

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

相关下载

更多

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
最新Python教程 从入门到精通
最新Python教程 从入门到精通

共4课时 | 22.4万人学习

Django 教程
Django 教程

共28课时 | 3.7万人学习

SciPy 教程
SciPy 教程

共10课时 | 1.3万人学习

关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号