【问题标题】:AttributeError: 'NoneType' object has no attribute 'text' - pythonAttributeError:“NoneType”对象没有属性“文本”-python
【发布时间】:2018-11-12 11:39:18
【问题描述】:

所以我一直在尝试学习数据抓取,我正在使用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")

程序运行良好。这是为什么?没有 class=“价格”的 div。我真的很困惑。

【问题讨论】:

  • 这是一个span。您正在搜索div
  • 打印stockPrice的内容以检查每种情况下的结果
  • @PRMoureu 当我使用 class_= "priceText__1853e8a5" 打印 stockPrice 时,什么都没有
  • @Aran-Fey 但是当我使用 div, class_=price 时它为什么运行良好?
  • 这真是一个难题。少数人解决不了问题,但因为有声望就可以点击关闭按钮,这样就不好看了。

标签: python beautifulsoup attributeerror nonetype


【解决方案1】:

我以前从来没有刮过,但是有一个.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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-10-16
    • 2019-03-05
    • 1970-01-01
    • 1970-01-01
    • 2021-06-05
    • 2019-02-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多