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

MTG卡牌价格爬虫:如何将HTML返回结果转换为float类型?

Fixing Your MTG Price Crawler: Converting Price Text to Float

Hey there, let's break down what's going wrong and fix your crawler step by step!

The Core Issues

  1. You're trying to convert a ResultSet to float: When you use findChildren() or find_all(), BeautifulSoup returns a collection of elements (a ResultSet, which acts like a list). You can't convert the whole list to a float directly—you need to process each individual element in the list first.
  2. The price text includes extra content: The output "PAPER 69.78" has the label "PAPER" attached, so you need to extract just the numeric part before converting to float.

Fixed Code with Explanations

Here's the revised code that addresses both problems, plus some cleanup to avoid redundant code:

import requests
from bs4 import BeautifulSoup

number = int(input("Enter the amount of cards: "))
card_list = {}

# Collect card names and sets
for i in range(number):
    card_names = input("Enter the card name: ")
    set_names = input("Enter the respective card set: ")
    card_list[card_names] = set_names

# Fetch and process each card's price
for card_name, set_name in card_list.items():
    url = f"https://www.mtggoldfish.com/price/{set_name}/{card_name}#paper"
    page = requests.get(url)
    soup = BeautifulSoup(page.content, 'html.parser')
    
    # Get the price container (no need for multiple find calls)
    price_boxes = soup.find_all("div", class_="price-box paper")
    
    for price_box in price_boxes:
        # Extract the full text and split into parts
        full_price_text = price_box.get_text().strip()
        # Split by whitespace, take the second element (the numeric price)
        price_str = full_price_text.split()[1]
        # Convert to float for math operations
        price_float = float(price_str)
        
        # Now you can use this float for calculations!
        print(f"{card_name} (Paper): ${price_float}")
        # Example math operation: calculate total for 2 copies
        print(f"Total for 2 copies: ${price_float * 2:.2f}\n")

Key Changes Made

  • Removed redundant find calls: We directly target the price-box paper class in one find_all() instead of nesting multiple searches.
  • Processed the price text: Using strip() to clean up extra whitespace, then split() to separate "PAPER" from the numeric value. We take the second item in the split list (index 1) since split() turns "PAPER 69.78" into ["PAPER", "69.78"].
  • Converted to float safely: Now that we have just the numeric string, converting to float() works without errors.
  • Added f-strings for cleaner URL building and output: Makes the code easier to read and maintain.

Optional: Add Error Handling

To make your crawler more robust (in case a card/set isn't found, or the price format changes), you can add try-except blocks:

for price_box in price_boxes:
    try:
        full_price_text = price_box.get_text().strip()
        price_str = full_price_text.split()[1]
        price_float = float(price_str)
        print(f"{card_name} (Paper): ${price_float}")
    except (IndexError, ValueError):
        print(f"Could not extract price for {card_name} in set {set_name}")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 16:42:44