无法获得BeautifulSoup正确(Python和XML(Excel网络)的html文件)识别列

问题描述:

我与一些这种格式的文件(消除造型HTML)工作:无法获得BeautifulSoup正确(Python和XML(Excel网络)的html文件)识别列

<html xmlns:x="urn:schemas-microsoft-com:office:excel"> 
 

 
<head> 
 
    <meta name="Generator" content="SAS Software Version 9.3, see www.sas.com"> 
 
    <meta http-equiv="Content-type" content="charset=windows-1252"> 
 
</head> 
 

 
<body> 
 
    <table class="table"> 
 
    <colgroup> 
 
     <col> 
 
     <col> 
 
      <col> 
 
      <col> 
 
    </colgroup> 
 
    <colgroup> 
 
     <col> 
 
     <col> 
 
    </colgroup> 
 
    <thead> 
 
     <tr> 
 
     <td class="header" rowspan="2" colspan="4" scope="colgroup">&nbsp;</td> 
 
     <td class="header" colspan="2" scope="colgroup">SubDistrict</td> 
 
     </tr> 
 
     <tr> 
 
     <td class="header" scope="col">Title1 
 
      <br> 
 
      <br> 
 
     </td> 
 
     <td class="header" scope="col">Title2 
 
      <br> 
 
      <br> 
 
     </td> 
 
     </tr> 
 
    </thead> 
 
    <tbody> 
 
     <tr> 
 
     <td class="rowheader" rowspan="12" scope="rowgroup">M1</td> 
 
     <td class="rowheader" scope="row">1.1</td> 
 
     <td class="rowheader" scope="row">var1</td> 
 
     <td class="rowheader" scope="row">TOTAL</td> 
 
     <td class="data">7</td> 
 
     <td class="data">7</td> 
 
     </tr> 
 
     <tr> 
 
     etc...

在浏览器中,他们似乎是这样的:

enter image description here

而且我已经写在Beautifu以下升汤,我的品牌新:

def read_xls(file): 
 
    f = open(file) 
 
    soup = BeautifulSoup(f.read(), 'html.parser') 
 
    
 
    table = soup.find_all('table') 
 
    #table[0].thead.find_all('tr')[1].td.get_text() 
 
    
 
    data = [] 
 
    for tr in table[0].find_all('tr'): 
 
     temp = [] 
 
     for td in tr.find_all('td'): 
 
      temp.append(td.get_text()) 
 
     data.append(temp) 
 
    return pd.DataFrame(data)

但我的代码是导致显著列对齐问题:

enter image description here

,关于如何提高任何意见我的BeautifulSoup代码来解析这个更正确?谢谢。

+0

这是一个公共页面你解析,你能分享一个链接,以便我们可以有一个完整的表进行试验吗?谢谢! – alecxe

+0

这是一个公共页面,但文件只能批量下载(这是印度*网站)。这里的网址给他们的拉链,但:https://nrhm-mis.nic.in/HMISReports/frmDownload.aspx?download=wqJDHZVkFe7jkTbCvX6Y8yY/TJhbpm1W2WyEC0VNP45GkBd3SMIF9lTO72QMVWpbsOV3CTZI2vax5pHgYnOuy9YaO9awMH375sHMUU9gsaYSKaohEyfuL8V4bOKsipiCqtF3FX53YVkGFwVd75UVv1PkPUmN66XUM2GSt1L2S6k= – user1318135

+0

@alecxe这里只是1文件:HTTPS://www.dropbox。 com/s/pr5xw0reryf943k/J%20-%20Sundargarh_January.html?dl = 0 – user1318135

如果我深知这是你想要提取什么:

enter image description here

你应该可以用下面的代码获得它:

def read_xls(file): 
    f = open(file) 

    soup = BeautifulSoup(f.read()) 
    tbody = soup.find('tbody') 
    data = [] 
    trs = tbody.findAll('tr') 
    for tr in trs: 
     tds = tr.findAll('td') 
     for td in tds: 
      data.append(td.text) 

    return pd.DataFrame(data).T 
+0

我想提取整个表格,使用它在html中呈现的相同组织,但是作为数据框。这说明了吗? – user1318135

+0

你有没有试过df = pd.read_html()?作为参数从文件中使用你的html代码。 – pawelty

+0

是的,它呈现类似于此。但是,它有点糟糕,因为它也错过了列标​​题。 – user1318135