2017-01-15 10 views
0

コメント内にテーブルを持つWebページを解析しようとしています。私はコメントのテーブルの列とデータを取得する方法を把握することはできません。以下は、htmlソースの一部です:Pythonでhtmlコメント内のテーブルを取得

<div id="all_info" class="table_wrapper setup_commented commented"> 
    <div class="section_heading"> 
     <span class="section_anchor" id="id_link" data-label="interesting data"/> 
     <h2>blah, blah</h2>  
     <div class="section_heading_text"> 
      <ul> <li>* indicates something important</li></ul> 
     </div>    
    </div> 
    <div class="placeholder"/> 
    <!-- 
     <div class="table_outer_container"> 
     <div class="overthrow table_container" id="div_info"> 
     <table class="sortable stats_table" id="info" data-cols-to-freeze=1> <caption>Interesting data Table</caption> 
      <colgroup><col><col><col><col><col><col><col><col><col><col><col><col><col><col><col><col><col><col></colgroup> 
      <thead> 
       <tr class="over_header"> <td> these are discard filler headers</td> 
       </tr> 
       <tr> <td> there are multiple entries here for headers </td> 
       </tr> 
      </thead> 
      <tbody> 
       <tr ><td> Lots of data here in series of columns </td> 
       </tr> 
      </tbody> 
     </table> 
     </div> 
     </div> 
    --> 
</div> 

私はPyQueryを使用していますが、他のソリューションにも対応しています。私は上記示したテキストでくれPyQueryオブジェクトを取得し

from pyquery import PyQuery as pq 
import requests 

doc = pq(requests.get(url).content) 
table = doc('#all_info') 

を次のようにこれまでのところ私は、HTMLからPyQueryドキュメントを取得します。私はコメントテキストを分離するために使用できるetreeも見つけましたが、テキスト内のhtmlマークアップを分離する能力がなくなりました。そのコードは次のとおりです。

from lxml import etree 
tree = etree.fromstring(str(table)) 
comments = tree.xpath('//comment()') 
for c in comments: 
    print c 

メモリストには1つのコメントしかありません。

誰かがこれに接近するための良い方法について他のアイデアを持っていますか?私が考えているのは、コメントマークアップを削除して、コメント内のすべてを有効なhtmlとして扱うことです。しかし、私はそれを行う方法を理解することができず、オブジェクトを見つけるためにPyQueryを使用する能力を維持していませんでした。私はスープや他のものを使用することにオープンしています。

答えて

1

ドキュメントごとに1つのだけのコメントは確かに存在する場合、単にBeautifulSoupまたはものは何でも解析のために使用する文字列を渡す前に、それを削除は:

doc = doc.replace("<!--","").replace("-->","") 
+0

あなたが正しかった、私はちょうど上で、このいずれかを答えるに非常に近かったです私自身。 'コメント= etree.tostring'、 'contents = comment.replace(" <! - "、" ")。replace(" - > "、") '、 'テーブル= pq(内容) '。 ありがとう! – exballer

関連する問題