2017-04-11 99 views
0

我试图得到结果的表使用此代码检索的资料:如果你不是在英国Python和熊猫

import pandas as pd 
url = 'https://www.betfair.co.uk/sport/football' 
df = pd.read_html(url, header = None) 
df[0] 

的URL可能会有所不同。

我认为它会像这样的代码,它完美的工作(我得到的表)为我。

import pandas as pd 
url = 'https://en.wikipedia.org/wiki/Opinion_polling_for_the_French_presidential_election,_2017' 
df = pd.read_html(url, skiprows=3) 
df[0] 

在第一个例子中,HTML是围绕<ul>,并<li>组织。

在第二个,它是一个适当的表。

我该如何调整大熊猫以获得第一种情况下的数据?

回答

2

不幸的是,pandas.read_htmldocs)仅提取从HTML表格数据:

import pandas as pd 
html = '''<html> 
      <body> 
       <table> 
       <tr> 
        <th>Col1</th> 
        <th>Col2</th> 
       </tr> 
       <tr> 
        <td>Val1</td> 
        <td>Val2</td> 
       </tr> 
       </table> 
      </body> 
      </html>''' 
dfs = pd.read_html(html) 
df[0] 

输出:

0  1 
0 Col1 Col2 
1 Val1 Val2 

对于其中我们的HTML包含一个无序列表代替第二种情况下,现有的熊猫功能将不起作用。您可以使用HTML解析库(如 BeautifulSoup4)解析列表(以及它的所有子项),并逐行构建数据帧。这里有一个简单的例子:

import pandas as pd 
from bs4 import BeautifulSoup 

html = '''<html> 
      <body> 
       <ul id="target"> 
       <li class="row"> 
        Name 
        <ul class="details"> 
        <li class="Col1">Val1</li> 
        <li class="Col2">Val2</li> 
        </ul> 
       </li> 
       </ul> 
      </body> 
      </html>''' 

# Parse the HTML string 
soup = BeautifulSoup(html, 'lxml') 

# Select the target <ul> and build dicts for each row 
data_dicts = [] 
target = soup.select('#target')[0] 
for row in target.select('.row'): 
    row_dict = {} 
    row_dict['name'] = row.contents[0].strip() # Remove excess whitespace 
    details = row.select('.details') 
    for col in details[0].findChildren('li'): 
     col_name = col.attrs['class'][0] 
     col_value = col.text.strip() 
     row_dict[col_name] = col_value 
    data_dicts.append(row_dict) 

# Convert list of dicts to dataframe 
df = pd.DataFrame(data_dicts) 

输出:

Col1 Col2 name 
0 Val1 Val2 Name 

findChildrenselect一些组合应该让你提取你链接的网站的基于表的各子组件。 BeautifulSoup有很多挖掘HTML的方法,所以我强烈建议通过一些例子来研究一下,如果你试图解析出一组特定的元素,就会看到文档。