2017-10-07 9 views
0

私は、HTMLを解析してテキストを取り出し、各単語(または潜在的には各テキストスニペット)とともに表示されるタグのリストを返したいと思います。Pythonがタグリストを持つHTML戻り単語を解析する

(("Blah", "em"), 
("blah", "em"), 
("blah", "em"), 
("blah", ""), 
("again", ""), 
("and", "i"), 
("then", "i"), 
("again", "i")) 

か::それは何か返します

<em>Blah blah blah</em> blah again <i>and then again</i> 

:このHTMLを与え例えば 、

(("Blah blah blah", "em"), 
    ("blah again", ""), 
    ("and then again", "i")) 

はのためのツールやそれを行うための簡単な方法はありますか?

おかげ

答えて

0

あなたはあなたがタグのスタックでループを作成することができます。この

>>> title = quote.css("span.text::text").extract_first() 
>>> title 
'“The world as we have created it is a process of our thinking. It cannot be changed without changing our thinking.”' 
>>> author = quote.css("small.author::text").extract_first() 
>>> author 
'Albert Einstein' 
+0

これは役に立ちそうです。私はスタイリングタグと一緒に単語を抽出したいと思います。 –

0

ような何かを行うことができ、このhttps://scrapy.org/

<div class="quote"> 
    <span class="text">“The world as we have created it is a process of our 
    thinking. It cannot be changed without changing our thinking.”</span> 
    <span> 
     by <small class="author">Albert Einstein</small> 
     <a href="/author/Albert-Einstein">(about)</a> 
    </span> 
    <div class="tags"> 
     Tags: 
     <a class="tag" href="/tag/change/page/1/">change</a> 
     <a class="tag" href="/tag/deep-thoughts/page/1/">deep-thoughts</a> 
     <a class="tag" href="/tag/thinking/page/1/">thinking</a> 
     <a class="tag" href="/tag/world/page/1/">world</a> 
    </div> 
</div> 

のために使用することができますあなたがタグを取得するとスタックにプッシュします。通常の単語は、スタックと単語の最後の項目をタプルとしてリストに追加します。リストが空白の場合は、タプルのタグの代わりに空の文字列を使用し、終了タグを取得するとスタックの最後の項目をポップします。 (スタックでは、私はPythonのリストを使用して、アイテムを追加したり削除したりするためのプッシュ/ポップアップ機能を使用しています)

+0

それは私が考えていたことです、私はちょうどそのような何かが既に存在することを望んでいました。 –

+0

おそらくhtmlパーサーがありますが、おそらく出力(おそらくツリー)とは異なるデータ構造を与えるでしょう – user8552411

+0

これは質問への答えを提供しません。十分な[評判](https://stackoverflow.com/help/whats-reputation)があれば、[投稿にコメントする]ことができます(https://stackoverflow.com/help/privileges/comment)。代わりに、[質問者から明確にする必要のない回答を提供する](https://meta.stackexchange.com/questions/214173/why-do-i-need-50-reputation-to-comment-what-c​​an -i-do-instead) - [レビューから](https://stackoverflow.com/review/first-posts/17657789) – Sand

関連する問題