AttributeError:' NoneType'对象没有属性' text' - 蟒蛇

时间:2018-06-02 15:38:59

标签: python beautifulsoup attributeerror nonetype

所以我一直在尝试学习数据抓取,并且我正在使用this stock website

当我检查元素价格时,它显示:

<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")

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

1 个答案:

答案 0 :(得分:0)

我以前从来没有抓过,但是.get_text() method

使用如下:

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)