【发布时间】:2022-01-21 06:37:49
【问题描述】:
我正在尝试从空 span 元素中的 span 元素中获取文本并在 python 中显示它们。我正在使用 bs4 并且似乎只能通过类获取 span 元素的子元素。有什么想法吗?
<span class="css-w8p71j">
<span>
<span>-$1.12</span>
<span>(-0.65%)</span>
</span>
</span>
实际的python代码
#imports
from bs4 import BeautifulSoup
import requests
from requests.api import get
#variables
link = 'HELP'
url = 'https://robinhood.com/stocks/'
runAgain = 'True'
#functions
def select():
global link
link = input('Input the stock ticker symbol or cmd for a list of commands: ').upper()
print(link)
if(link == 'HELP'):
print('Help: use a browser to see a stocks ticker symbol, for instance AAPL for Apple. Do list in input field to see list of stock ticker symbols.')
return
elif(link == 'LIST'):
print('List:\nAAPL:\tApple\nSPY:\tS&P 500 ETF\nTSLA:\tTesla\nAMC:\tAMC Entertainment\nF:\tFord Motor\nSNDL:\tSundial Growers\nMSFT:\tMicrosoft\nAMZN:\tAmazon\nDIS:\tDisney\nNIO:\tNIO')
return
elif(link == 'CMD'):
print('help: gives information on how to input a stock via ticker symbol\nlist: gives a list of a few major stocks and their ticker symbol\ncmd: yields this information')
return
getInfo()
def getInfo():
global link
global url
page = requests.get(url+link)
if(page.status_code == 404):
print('Stock not found or available!')
return
soup = BeautifulSoup(page.content, 'html.parser')
value = soup.find("span", class_='up')
value = (value['aria-label'])
# change = soup.find('span', class_='css-w8p71j')
#this is the problem area
for item in soup.select("*[class^='css-w8p71j']"):
child = item.find_all("span")
print(child)
# print(child[1].text)
print('Current stock price of '+link+': '+str(value)+'\nTotal change today: ')
#main
while(runAgain == 'True'):
select()
runAgain = input('Would you like to run again? y/n: ').upper()
if(runAgain == 'Y'):
runAgain = 'True'
为背景信息添加了更多的python代码
【问题讨论】:
-
请使用api,这样从页面中抓取数据是浪费时间。 data.nasdaq.com/tools/api
标签: python beautifulsoup