2017-10-07 50 views
0

我想解析HTML,獲取文本,並返回每個單詞(或潛在的每個文本片段)附帶的標籤列表。 例如,給定這個HTML:Python用標籤列表解析HTML返回單詞

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

這將返回類似:

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

或:

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

是否有工具或一個簡單的方法來做到這一點?

感謝

回答

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> 

你可以做這樣的事情

>>> 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

您可以創建一個循環使用的標籤棧當你到達某個標籤時,將它推到堆棧上普通單詞將堆棧中的最後一項和該單詞添加到您的列表中作爲元組。如果列表爲空,則當您到達結束標記時,將空字符串而不是標籤用於元組,以便彈出堆棧中的最後一項。 (按堆棧我的意思是在python列表中,只是使用push和pop函數來添加和刪除項目)

+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