python - 从 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 来获取例如值。
错误是:
- AttributeError:“NoneType”对象没有属性“find_previous”
- AttributeError:“列表”对象没有属性“文本”
- TypeError:select()得到了一个意外的关键字参数'attrs'
- 或者我只是得到了一个空列表 -> [ ]
解决方案
页面是动态的。您可以使用 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
推荐阅读
- arduino - 用于 NUCLEO-F446RE 的 STM32duino 时钟配置
- android - 滚动时GraphView的水平标签问题
- scala - 如何在合并中替换空值并添加
- javascript - jquery 检查父元素中是否有特定的文本,如果有,则在特定的预先存在的子元素之后添加子元素
- vb.net - VB.NET 在图片框中绘制与设备无关的位图
- python - 如何处理依赖的多个主要版本
- javascript - 交换两个 ngx-select 的值
- c - S32K146EVB 擦除/写入闪存时发生读取冲突
- json - 如何在pyspark中将rdd转换为嵌套的json
- php - 大型 php 站点地图(使用数据库连接)可以减慢/阻塞服务器吗?