python - 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')
解决方案
是的,你应该使用 .string 这个.string 和 .text 之间的区别 BeautifulSoup 解释了 .text 和 .string 之间的区别。不能在 bs4 版本 > 4.8.0 中使用 .text。
推荐阅读
- java - 在服务器上部署时java图形drawString错误字体
- java - 如何比较 if 语句中的布尔值与输出 Java
- macos - MacOS 上的 Arduino 禁用了我的 USB 端口
- javascript - 为 div 创建 cookie
- node.js - 原生 Promise 和 bluebird Promise 的区别
- jquery - 设置图像的 src 时显示/隐藏占位符
- javascript - 未捕获的类型错误:无法读取未定义的属性“toString”如何删除 rawMarkUp 中代码的依赖关系?
- javascript - 清除单元格 google sheet 脚本
- python - 如何使 cython 函数接受浮点或双数组输入?
- linux - Cannot compile example code in libpca