2012-04-14 110 views
6

從這個網站源之前提取文本:使用BeautifulSoup第一個孩子標籤

<div class="category_link"> 
    Category: 
    <a href="/category/personal">Personal</a> 
</div> 

我想提取文本Category:

下面是使用Python/BeautifulSoup(以輸出爲註釋我嘗試 - 之後#)

parsed = BeautifulSoup(sample_html) 
parsed_div = parsed.findAll('div')[0] 
parsed_div.firstText() # <a href="/category/personal">Personal</a> 
parsed_div.first() # <a href="/category/personal">Personal</a> 
parsed_div.findAll()[0] # <a href="/category/personal">Personal</a> 

我希望有一個「文本節點」可作爲第一個孩子。有關我如何解決這個問題的任何建議?

+1

'parsed_div.contents [0]' – Avaris 2012-04-14 16:37:35

回答

11

我確信以下應該做你想要

parsed.find('a').previousSibling # or something like that 

這將返回一個NavigableString實例,它是幾乎同樣的事情 作爲unicode實例什麼,但你可以叫上unicode到獲取一個 unicode對象。

我會看看我是否可以測試這一點,並讓你知道。

編輯:我只是證實了它的工作原理:

>>> from BeautifulSoup import BeautifulSoup 
>>> soup = BeautifulSoup('<div class=a>Category: <a href="/">a link</a></div>') 
>>> soup.find('a') 
<a href="/">a link</a> 
>>> soup.find('a').previousSibling 
u'Category: ' 
>>> 
+0

真棒!像魅力一樣工作 – 2012-04-14 14:58:36

相關問題