2010-08-09 127 views
2

我需要獲取頁面上包含特定字符串'abc123123'的所有表格行。使用beautifulSoup,試圖獲取其中包含字符串的所有表格行

該字符串位於TD內部,但如果其中包含'abc123123',則需要整個TR。

我嘗試這樣做:

userrows = s.findAll('tr', contents = re.compile('abc123123')) 

我不知道,如果內容寫入性能。

我的HTML看起來像:

<tr> 
    <td> 
    </td> 
    <td><table>.... abc123123 </table><tr> 
    .. 
</tr> 
<tr> 
.. 
</tr> 
.. 
.. 

回答

4

沒有,額外的關鍵字參數超出規定的那些(name, attrs, recursive, text, limit)均指屬性您要搜索的標籤

您不能搜索的同時nametext(如果指定text,BS忽略name),所以你需要單獨調用,如:

allrows = s.findAll('tr') 
userrows = [t for t in allrows if t.findAll(text=re.compile('abc123123'))] 

這裏我使用了一個列表理解因爲我假設你想要一個有關標籤對象的列表,如findAll本身給你。

+0

或者我可以做,如果沒有t.findAll(..)繼續感謝,現在試試吧! – Blankman 2010-08-09 01:20:58

+0

確定它不工作,因爲我正在尋找的文本實際上是在一個href標籤內...... hmm – Blankman 2010-08-09 02:17:45

+0

@Blankman,HTML中沒有'href'標籤,我想你是指'一個'標籤。在這種情況下,當然,在第二條語句中使用't.findall('a',href = re.compile('abc123123'))''。 – 2010-08-09 03:14:35

相關問題