如何解决BS4返回AttributeError:'NoneType'对象有时没有属性'text',该如何解决?
我写了一篇文章,试图从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')
解决方法
是的,您应该使用.string这个Difference between .string and .text BeautifulSoup解释了.text和.string之间的区别。在bs4版本> 4.8.0中不能使用.text。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。