首页 > 解决方案 > AttributeError:“NoneType”对象没有属性“文本”-python

问题描述

所以我一直在尝试学习数据抓取,我正在使用 这个股票网站

当我检查元素价格时,它表明:

<span class="priceText__1853e8a5">12,620.83</span>

因此,当我使用它并在 python 中编写它时:

stockPrice = soup.find('div', class_="priceText__1853e8a5")
price = stockPrice.text.strip()
print(price)

当我运行它时,它给了我以下错误:

price = stockPrice.text.strip()
AttributeError: 'NoneType' object has no attribute 'text'

但是,当我使用:

stockPrice = soup.find('div', class_="price")

该程序运行完全正常。这是为什么?没有 class = "price" 的 div。我真的很困惑。

标签: pythonbeautifulsoupattributeerrornonetype

解决方案


我以前从来没有刮过,但是有一种.get_text() 方法

使用如下:

from bs4 import BeautifulSoup
import requests
r = requests.get("https://www.bloomberg.com/quote/NYA:IND")
data = r.text
soup = BeautifulSoup(data, "lxml")

stockPrice = soup.find("div", class_="price")
print(stockPrice)
price = stockPrice.get_text()
print(price)

推荐阅读