首页 > 解决方案 > 从 Morningstar / BeautifulSoup 获取股票价格

问题描述

所以它正在发生。最后,我要问我关于 Stackoverflow 的第一个问题。

我正在尝试从 Morningstar ( https://www.morningstar.com/stocks/xnas/tsla/quote.html ) 获取股票的当前价格,我正在为此使用 Beautifulsoup。

在 HTML 代码中有一个唯一的 ID(“message-box-price”)。我想用它来获取价格,但不幸的是我找不到解决方案。如果有人可以帮助我,那就太好了。

我获取该网站的代码是:

import bs4
import requests

res = requests.get('https://www.morningstar.com/stocks/xnas/tsla/quote.html')
res.raise_for_status()
soup = bs4.BeautifulSoup(res.text, 'lxml')

我尝试了许多不同的方法,但我认为这些是最有希望的方法:

1号:

price = soup.find(id='message-box-price')
price2 = price.find_next()
print(price2)

2号:

price = soup.select("#message-box-price")
price2 = price.find_all_next()
print(price2)

3号:

price = soup.find_all(id="message-box-price")
print(price)

此外,我尝试了它的一些变体并使用 .text 来获取例如值。

错误是:

标签: pythonbeautifulsoupstockpricemorningstar

解决方案


页面是动态的。您可以使用 Selenium 打开页面,让它渲染,然后获取信息:

import pandas as pd
import bs4 
from selenium import webdriver 

url = 'https://www.morningstar.com/stocks/xnas/tsla/quote.html'

browser = webdriver.Chrome()
browser.get(url)

html = browser.page_source

soup = bs4.BeautifulSoup(html,'html.parser')

price = soup.find('div', {'id':'message-box-price'})
price2 = price.text.strip()
print(price2)

browser.close()

输出:

print(price2)
$312.21

推荐阅读