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
- You're trying to convert a
ResultSetto float: When you usefindChildren()orfind_all(), BeautifulSoup returns a collection of elements (aResultSet, 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. - 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
findcalls: We directly target theprice-box paperclass in onefind_all()instead of nesting multiple searches. - Processed the price text: Using
strip()to clean up extra whitespace, thensplit()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
相关产品推荐
相关产品推荐

