将CME价格数据提取到Python 3.6.8中

时间:2019-06-09 19:36:19

标签: python web-scraping beautifulsoup python-requests urllib3

我对Python比较陌生,因此如果这是一个“布什联盟”问题,我深表歉意。

我正在尝试从以下网站检索WTI期货价格: https://www.cmegroup.com/trading/energy/crude-oil/west-texas-intermediate-wti-crude-oil-calendar-swap-futures_quotes_globex.html

我应该使用哪个库?从网站提取输出后,我需要如何调整输出?

当前在pandas,numpy,requests,urllib3,BeautifulSoup和json库中在Python 3.6.8中运行。我不确定这些库是否正确,是否应该使用哪些功能。

这是代码的基本版本:

wtiFutC = 'https://www.cmegroup.com/trading/energy/crude-oil/west-texas-intermediate-wti-crude-oil-calendar-swap-futures_quotes_globex.html'
http = urllib3.PoolManager()
response2 = http.request('GET', wtiFutC)
print(type(response2.data)) #check the type of the data produced - bytes
print(response2.data) #prints out the data

soup2 = BeautifulSoup(response2.data.decode('utf-8'), features='html.parser')
print(type(soup2)) #check the type of the data produced - 'bs4.BeautifulSoup'
print(soup2) #prints out the BeautifulSoup version of the data

我想要一种方法来查看整个曲线上WTI期货的“最后”价格。相反,我看到的是这样的:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<!--[if (gt IE 9) |!(IE)]><!-->
<html class="cmePineapple no-js" lang="en" xml:lang="en" 
xmlns="http://www.w3.org/1999/xhtml">
<!--<![endif]-->

任何帮助或指导将不胜感激。非常感谢! :)

3 个答案:

答案 0 :(得分:0)

该网页中的数据是由javascript生成的,因此很难使用requests之类的包提取数据。  如果这没什么大不了的,我建议您寻找使用最少或不使用JavaScript的其他数据源。然后使用requests获取网页源并从中提取数据。

您可以使用BeautifulSoupre(在某些情况下甚至是pandas之类的库中提取数据,并将其提供给numpy或{{1} },如果您想分析数据并进行计算。

否则,我建议您查看pandas以获得JavaScript支持。

答案 1 :(得分:0)

使用Requests-HTML。如果您已经熟悉请求,那么这是一个很好的资源。

答案 2 :(得分:0)

使用页面执行的端点并从json中解析出感兴趣的列(和日期)

import requests

r = requests.get('https://www.cmegroup.com/CmeWS/mvc/Quotes/Future/4707/G?quoteCodes=null&_=1560171518204').json()
last_quotes = [(item['expirationDate'], item['last']) for item in r['quotes']]