2012-03-22 73 views
1

給出的例子HTML字符串找不到標籤和正則表達式BeautifulSoup

<table> 
<tr> 
<td class="td" height="25">Upstream Power</td> 
<td class="td">25.2 dBmV</td> 
<td class="td">49.2 dBmV</td> 
</tr> 
</table> 

我可以用查找文本:

soup.find_all(text=re.compile("Power")) 

但要找到整個標籤沒有找到任何東西。我錯過了什麼?

soup.find_all("td",text=re.compile("Power")) 

回答

0

在BS3,該方法是findAllfind_all

>>> markup = '''<table> 
... <tr> 
... <td class="td" height="25">Upstream Power</td> 
... <td class="td">25.2 dBmV</td> 
... <td class="td">49.2 dBmV</td> 
... </tr> 
... </table>''' 
>>> from BeautifulSoup import BeautifulSoup as bs 
>>> soup = bs(markup) 
>>> import re 
>>> soup.findAll(text=re.compile('Power')) 
... [u'Upstream Power'] 

編輯:我看到,該方法was renamed in BS4。這似乎爲我工作確定:

>>> from bs4 import BeautifulSoup as bs 
>>> soup = bs(markup) 
>>> soup.find_all(text=re.compile('Power')) 
... [u'Upstream Power'] 

EDIT2:爲了使導航解析樹更容易,你可以use tag names

>>> soup.td.find_all(text=re.compile('Power')) 
... [u'Upstream Power'] 
+0

是soup.find_all(文= re.compile(」電源'))也適用於我,但爲什麼不soup.find_all(「td」,text = re.compile(「Power」))。我需要這樣的東西,因爲我想從這一點開始遍歷樹。 – CptanPanic 2012-03-22 19:24:10

+0

@CptanPanic:啊,我錯過了。我用更好的方式編輯答案,以獲得你想要的元素。 – bernie 2012-03-22 19:38:37