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

使用BeautifulSoup爬取PS商店报错:'NoneType'无get_text属性

解决PlayStation商店爬虫的AttributeError问题

嘿,我看到你遇到的问题了——这个AttributeError是因为你的代码直接对find()返回的None对象调用了get_text()方法。当页面上某个游戏没有折扣标签时,container.find()找不到对应的元素,就会返回None,这时候再调用get_text()自然就报错了。咱们一步步来修复这个问题:

问题根源

你的代码里有两处核心风险点:

  • 直接对salePercentContainer调用get_text(),没有先检查它是否存在
  • 价格部分的逻辑也没有妥善处理元素不存在的情况
    另外,你用的折扣标签选择器可能不太准确,PlayStation商店的class名可能有变动,比如discount-badge-- undefined这种带空格的class写法很容易出问题。

修复后的代码

from urllib.request import urlopen as uReq
from bs4 import BeautifulSoup as soup

my_url = 'https://store.playstation.com/en-ca/category/85448d87-aa7b-4318-9997-7d25f4d275a4/1'
uClient = uReq(my_url)
page_html = uClient.read()
uClient.close()

page_soup = soup(page_html, "html.parser")
containers = page_soup.find_all("section", {"class": "ems-sdk-product-tile__details"})

for container in containers:
    # 获取游戏标题:先检查元素是否存在,避免None调用方法
    title_elem = container.find("span", {"class": "ems-sdk-product-tile__title"})
    title = title_elem.get_text(strip=True) if title_elem else "Unknown Title"
    
    # 获取折扣率:先判断折扣标签是否存在,再提取文本
    sale_percent_elem = container.find("span", class_="discount-badge")
    sale_percent = sale_percent_elem.get_text(strip=True) if sale_percent_elem else "No Discount"
    
    # 处理价格:区分有折扣(显示原价+现价)和无折扣的情况
    original_price_elem = container.find("strike")
    if original_price_elem:
        original_price = original_price_elem.get_text(strip=True)
        current_price_elem = container.find("span", {"class": "psw-m-r-2"})
        current_price = current_price_elem.get_text(strip=True) if current_price_elem else "Unknown Price"
        price = f"Original: {original_price}, Current: {current_price}"
    else:
        current_price_elem = container.find("span", {"class": "price"})
        price = current_price_elem.get_text(strip=True) if current_price_elem else "Unknown Price"
    
    print(f"Title: {title}")
    print(f"Discount: {sale_percent}")
    print(f"Price: {price}\n")

关键改进点

  • 安全的元素访问:每次调用get_text()前,先判断元素是否存在(用三元表达式简化逻辑)
  • 更稳定的选择器:用class_="discount-badge"替代复杂的带空格class,避免页面class名变动导致找不到元素
  • 清晰的价格逻辑:分开处理有折扣和无折扣的场景,输出更直观
  • strip=True:自动去除文本前后的空格、换行,让输出更整洁

这样修改后,即使遇到没有折扣的游戏,代码也不会报错,而是会友好显示"No Discount",价格部分也能正确适配各种情况。

内容的提问来源于stack exchange,提问作者Joe C.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 08:29:46