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

BeautifulSoup报错:'NoneType'对象无'text'属性,求解决方案

解决BeautifulSoup解析Google Play页面时的AttributeError问题

你遇到的AttributeError: 'NoneType' object has no attribute 'text',本质是soup.find('h1', attrs={'class': 'AHFaub'})返回了None——也就是说BeautifulSoup没找到你指定的元素。核心原因要么是Google Play的反爬机制拦截了你的请求,要么是页面的CSS类名已经更新。

解决步骤:

  1. 添加请求头模拟浏览器
    Google Play会识别非浏览器的请求,直接返回无有效内容的页面。给requests.get添加User-Agent头,模拟真实浏览器请求:
headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36'
}
response = requests.get(url, headers=headers)
  1. 验证页面结构是否变化
    Google Play的页面元素类名可能会更新,你可以先打印response.text查看实际返回的HTML内容,或者用浏览器F12开发者工具重新定位应用名称、评分的元素选择器。比如当前应用名称可能在h1标签的Fd93Bb类下,评分可能在iXRFPc类的元素里。

  2. 添加异常处理避免崩溃
    即使处理了请求头,也可能因为网络或页面变化导致元素找不到,所以要先判断元素是否存在再调用.text:

# 提取应用名称
app_name_elem = soup.find('h1', attrs={'class': 'AHFaub'})
app_name = app_name_elem.text.strip() if app_name_elem else '未找到应用名称'

# 提取应用评分
app_rating_elem = soup.find('div', attrs={'class': 'BHMmbe'})
app_rating = app_rating_elem.text.strip() if app_rating_elem else '未找到评分'

修改后的完整代码:

import requests
from bs4 import BeautifulSoup

url = 'https://play.google.com/store/apps/details?id=in.startv.hotstar'

# 添加浏览器请求头
headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36'
}
response = requests.get(url, headers=headers)
soup = BeautifulSoup(response.content, 'html.parser')

# 安全提取应用名称
app_name_elem = soup.find('h1', attrs={'class': 'AHFaub'})
app_name = app_name_elem.text.strip() if app_name_elem else '未找到应用名称'

# 安全提取应用评分
app_rating_elem = soup.find('div', attrs={'class': 'BHMmbe'})
app_rating = app_rating_elem.text.strip() if app_rating_elem else '未找到评分'

print('App Name:', app_name)
print('App Rating:', app_rating)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 08:07:50