2014-11-24 83 views
0

我试着用熊猫读取ec2定价表格。基于documentation我期望DataFrames的列表,但得到一个表作为列表。pandas.read_html只返回一个表格

代码示例

import pandas 
link = 'http://aws.amazon.com/ec2/pricing/' 
data = pandas.read_html(link) 
print type(data) 
print data[0] 

输出

<type 'list'> 
           0     1    2 
0 Reserved Instance Volume Discounts    NaN    NaN 
1   Total Reserved Instances Upfront Discount Hourly Discount 
2     Less than $250,000    0%    0% 
3    $250,000 to $2,000,000    5%    5% 
4   $2,000,000 to $5,000,000    10%    10% 
5    More than $5,000,000  Contact Us  Contact Us 

环境:

  • Ubuntu的14.10
  • 蟒蛇2.7.8
  • 大熊猫0.14.1
+0

什么'类型(数据[0])'?你链接的文档'read_html'将返回一个DataFrames列表,这就是你得到的:一个包含1个DataFrame的列表。通过检查源代码,它看起来像是唯一真正的HTML表(在tr URL中使用'tr','td')是预留实例卷折扣。 – wflynny 2014-11-24 20:55:29

回答

1

http://aws.amazon.com/ec2/pricing/使用JavaScript来填写表中的数据。

不像你所看到的,当你在链接指向你的GUI浏览器,数据丢失,如果你使用的urllib2下载HTML:(然后搜索内容为<table>标签)

import urllib2 
response = urllib2.urlopen(link) 
content = resonse.read() 

要处理JavaScript,您需要使用Selenium, 或WebKit或Spidermonkey等自动浏览器引擎。

在这里被使用溶液硒:

import selenium.webdriver as webdriver 
import contextlib 
import pandas as pd 
@contextlib.contextmanager 
def quitting(thing): 
    yield thing 
    thing.quit() 

with quitting(webdriver.Firefox()) as driver: 
    link = 'http://aws.amazon.com/ec2/pricing/' 
    driver.get(link) 
    content = driver.page_source 
    with open('/tmp/out.html', 'wb') as f: 
     f.write(content.encode('utf-8')) 
    data = pd.read_html(content) 
    print len(data) 

产生

238 
+0

感谢您指出JavaScript,但是我的代码示例有问题。有一个错误的配置文件“ WebDriverException:消息:'无法加载配置文件。配置文件目录:/ tmp/user/1001/tmpToFbg5” – Wawrzek 2014-11-25 09:52:34

+0

这听起来像[您的版本之间的不兼容](http:// stackoverflow.com/q/20957968/190597)Selenium和Firefox。 – unutbu 2014-11-25 12:57:26