【问题标题】:BS4 returning AttributeError: 'NoneType' object has no attribute 'text' sometimes, how to solve this?BS4 返回 AttributeError: 'NoneType' object has no attribute 'text' 有时,如何解决这个问题?
【发布时间】:2021-01-06 11:15:31
【问题描述】:

我写了一篇文章,试图从 yahoo Finance 获取一些数据。但是,在能够检索股票数据(价格和价格变化)后,第一次尝试在开始时失败了。它给出了 NoneType 错误。然后我再次运行它,它实际上能够突然检索到该数据并继续检索更多数据并在中途某处失败并出现相同的错误。我觉得很奇怪,因为该属性文本存在于 html 中。特别奇怪的是,它无需调整即可在第二次尝试中找到它。此外,它们都在同一页面上,所以我不需要等待一些。 这是错误:

price = soup_ticker.find('span', class_='Trsdu(0.3s) Fw(b) Fz(36px) Mb(-4px) D(ib)').text AttributeError: 'NoneType' 对象没有属性 'text'

这是具体的html:

<span class="Trsdu(0.3s) Fw(b) Fz(36px) Mb(-4px) D(ib)" data-reactid="32">22.12</span>

这是我的代码。请注意,我是初学者,这都是出于教育目的。我知道可能有一百万种方法可以比我在下面所做的更好地做到这一点。感谢您提前提供的帮助和您的知识!

from django.core.management.base import BaseCommand
from urllib.request import urlopen
from bs4 import BeautifulSoup
import json
from scraping.models import StockData

import re


class Command(BaseCommand):
    help = "Collects a stock ticker, price, price change and date"

    # define logic of command
    def handle(self, *args, **options):
        # collect html
        html = urlopen('http://eoddata.com/stocklist/NASDAQ/A.htm')

        regex = re.compile("Display Quote & Chart for")
        regex_price = re.compile("Trsdu(0.3s) Fw(500) Pstart(10px)")
        soup = BeautifulSoup(html, 'html.parser')
        # grab all postings
        td = soup.find_all("td")
        for tag in td:
            for anchor in tag.find_all('a', {'title': regex}):
                ticker = anchor.text
                html_ticker = urlopen("https://finance.yahoo.com/quote/" + ticker + "/")
                soup_ticker = BeautifulSoup(html_ticker, 'html.parser')
                price = soup_ticker.find('span', class_='Trsdu(0.3s) Fw(b) Fz(36px) Mb(-4px) D(ib)').text
                change = soup_ticker.find('div', class_="D(ib) Mend(20px)").find_all('span')[1].text

                try:
                    # save in db
                    StockData.objects.create(
                        ticker=ticker,
                        price=price,
                        change=change,
                    )
                    print('%s added' % (ticker,))
                except:
                    print('%s already exists' % (ticker,))
            self.stdout.write('job complete')

【问题讨论】:

  • 你可以用字符串代替,这应该可以解决你的问题。

标签: python django beautifulsoup nonetype


【解决方案1】:

是的,你应该使用 .string 这个Difference between .string and .text BeautifulSoup 解释了 .text 和 .string 之间的区别。无法在 bs4 版本 > 4.8.0 中使用 .text。

【讨论】:

  • Thnx 的评论,我已经尝试过了,但最终还是出现了同样的错误。 price = soup_ticker.find('span', class_='Trsdu(0.3s) Fw(b) Fz(36px) Mb(-4px) D(ib)').string AttributeError: 'NoneType' object has no attribute 'string' 但在出现此错误之前,它确实说:某些字符无法解码,并被替换为替换字符。这可能对你说些什么吗?我也会检查stackoverflow,看看是否有关于那个替换字符的一些线索。
猜你喜欢
  • 1970-01-01
  • 2021-04-06
  • 2021-08-22
  • 1970-01-01
  • 2019-06-04
  • 1970-01-01
  • 2022-12-15
  • 1970-01-01
  • 2022-12-04
相关资源
最近更新 更多