首页 > 解决方案 > BS4返回AttributeError:'NoneType'对象有时没有属性'text',如何解决这个问题?

问题描述

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

price = soup_ticker.find('span', class_='Trsdu(0.3s) Fw(b) Fz(36px) Mb(-4px) D(ib)').text AttributeError: 'NoneType' object has no attribute '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')

标签: pythondjangobeautifulsoupnonetype

解决方案


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


推荐阅读