python - 如何使用BeautifulSoup在网站上获取实时股票价格?

标签 python html beautifulsoup element

我正在做一个项目来获取 http://www.jpmhkwarrants.com/en_hk/market-statistics/underlying/underlying-terms/code/1 上的实时股票价格.我在网上搜索并尝试了几种获取价格的方法,但仍然失败。这是我的代码:

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 module解决?

最佳答案

查看页面源码你会看到这样的html

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

我们想要的span在索引2中,选择它

price = soup.select('.table.detail td span')[1]
print(price.text)

演示:

<script type="text/javascript" src="//cdn.datacamp.com/dcl-react.js.gz"></script>

<div data-datacamp-exercise data-lang="python">
	<code data-type="sample-code">
  from bs4 import BeautifulSoup
  from urllib.request import 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')
        price = soup.select('.table.detail td span')[1]
        print(price.text)

  getStockPrice()
	</code>
</div>

关于python - 如何使用BeautifulSoup在网站上获取实时股票价格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53531553/

相关文章:

html - 如何在文本周围制作一个紧密的单元格并展开空单元格?

html - 多个 CSS 背景

Python Pandas : Find a pattern in a DataFrame

python - 在 Python 中使用进度指示器迭代大文件?

html - 当鼠标触摸它时停止图像标记

python - BeautifulSoup 省略了页面正文

python - 如何去掉抓取数据的p标签

css - 用 BeautifulSoup 中的字符串替换字符串

python - 在每个单词前添加 Virgula

python - 在 Pandas 数据框中拆分字符串