Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/89.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何使用BeautifulSoup在网站上获取实时股价?_Python_Html_Beautifulsoup_Element - Fatal编程技术网

Python 如何使用BeautifulSoup在网站上获取实时股价?

Python 如何使用BeautifulSoup在网站上获取实时股价?,python,html,beautifulsoup,element,Python,Html,Beautifulsoup,Element,我正在做一个项目,以获得实时股票价格。我在网上搜索并尝试了几种方法来获取价格,但还是失败了。这是我的密码: def getStockPrice(): url = "http://www.jpmhkwarrants.com/zh_hk/market-statistics/underlying/underlying-terms/code/1" r = urlopen(url) soup = BeautifulSoup(r.read(), 'lxmll)

我正在做一个项目,以获得实时股票价格。我在网上搜索并尝试了几种方法来获取价格,但还是失败了。这是我的密码:

def getStockPrice():
      url = "http://www.jpmhkwarrants.com/zh_hk/market-statistics/underlying/underlying-terms/code/1" 
       r = urlopen(url)
      soup = BeautifulSoup(r.read(), 'lxmll)
      price = soup.find(id = "real_time_box").find({"span", "class":"price"})
      print(price)

输出为“无”。我知道价格是在上面的函数脚本,但我不知道如何获得价格。这可以通过beautifulsoup或else模块解决吗?

查看页面源代码,您将看到如下html

<div class="table detail">
    .....
    <div class="tl">即市走勢 <span class="description">前收市價</span>
    .....
    <td>買入價(延遲*)<span>82.15</span></td>
演示:



从bs4导入BeautifulSoup
从urllib.request导入urlopen
def getStockPrice():
url=”http://www.jpmhkwarrants.com/zh_hk/market-statistics/underlying/underlying-terms/code/1" 
r=urlopen(url)
soup=BeautifulSoup(r.read(),'html.parser')
价格=汤。选择('.table.detail td span')[1]
打印(price.text)
getStockPrice()

网站正在动态加载数据。你应该使用
selenium
(最简单)、
request html
Scrapy
来运行JavaScript,然后你就可以获得完整的数据。如果你可以从可用的python库中获得OHLC价格,为什么还要解析这些网站呢?@RosdyanaKusuma我不知道yahoo finance提供了python库。我现在就去看看。谢谢你的帮助remind@RosdyanaKusuma我从github中提取了这个项目,并运行了test.py,这给了我一系列错误。此外,雅虎金融是否提供欧洲和香港股票信息?似乎它只提供美国的股票信息。@WILLIAM,我曾经为我的出版物做过一项关于台湾、香港、英国和印度尼西亚股市预测的研究,这是下载ohlc价格的代码。谢谢你的回复。它显示索引错误:列表索引超出范围。我猜beautifulsoup是不可能获得价格的,因为它是javascript。奇怪的是,我在多台机器上尝试了它,它返回了预期的结果,你能试着运行上面的代码片段吗?非常感谢。我将“lxml”更改为“html.parser”作为演示代码后,它就可以工作了。您是否介意进一步解释一下为什么它可以直接解析价格,但不需要运行javascript函数并从中获取价格?再次感谢。数据来自
html
javascript
,它来自
html
,这是静态文本。我又有一个问题。为什么我不能以相同的方式获取div id=“real\u time\u box”中的数据?
price = soup.select('.table.detail td span')[1]
print(price.text)