2012-03-27 60 views
0

与BeautifulSoup不同的标识标签迭代这可能是一个简单的问题,但我想通过标签ID为迭代= dgrdAcquired_hyplnkacquired_0,dgrdAcquired_hyplnkacquired_1等我如何通过使用Python

是否有任何容易这样做的方式比我在下面的代码?麻烦的是这些标签的数量对于我所提到的每个网页都会有所不同。当每个网页可能有不同数量的标签时,我不确定如何获取这些标签中的文字。

html = """ 
<tr> 
<td colspan="3"><table class="datagrid" cellspacing="0" cellpadding="3" rules="rows" id="dgrdAcquired" width="100%"> 
<tr class="datagridH"> 
<th scope="col"><font face="Arial" color="Blue" size="2"><b>Name (RSSD ID)</b></font></th><th scope="col"><font face="Arial" color="Blue" size="2"><b>Acquisition Date</b></font></th><th scope="col"><font face="Arial" color="Blue" size="2"><b>Description</b></font></th> 
</tr><tr class="datagridI"> 
<td nowrap="nowrap"><font face="Arial" size="2"> 
<a id="dgrdAcquired_hyplnkacquired_0" href="InstitutionProfile.aspx?parID_RSSD=3557617&parDT_END=20110429">FIRST CHOICE COMMUNITY BANK                        (3557617)</a> 
</font></td><td><font face="Arial" size="2"> 
<span id="dgrdAcquired_lbldtAcquired_0">2011-04-30</span> 
</font></td><td><font face="Arial" size="2"> 
<span id="dgrdAcquired_lblAcquiredDescText_0">The acquired institution failed and disposition was arranged of by a regulatory agency. Assets were distributed to the acquiring institution.</span> 
</font></td> 
</tr><tr class="datagridAI"> 
<td nowrap="nowrap"><font face="Arial" size="2"> 
<a id="dgrdAcquired_hyplnkacquired_1" href="InstitutionProfile.aspx?parID_RSSD=104038&parDT_END=20110429">PARK AVENUE BANK, THE                         (104038)</a> 
</font></td> 
""" 
soup = BeautifulSoup(html) 
firm1 = soup.find('a', { "id" : "dgrdAcquired_hyplnkacquired_0"}) 
data1 = ''.join(firm1.findAll(text=True)) 
print data1 

firm2 = soup.find('a', { "id" : "dgrdAcquired_hyplnkacquired_1"}) 
data2 = ''.join(firm2.findAll(text=True)) 
print data2 

回答

1

我会做以下假设,如果有n这样的标签,它们的编号0...n

soup = BeautifulSoup(html) 
i = 0 
data = [] 
while True: 
    firm1 = soup.find('a', { "id" : "dgrdAcquired_hyplnkacquired_%s" % i}) 
    if not firm1: 
     break 
    data.append(''.join(firm1.findAll(text=True))) 
    print data[-1] 
    i += 1 
+0

谢谢阿龙。这工作完美。 – myname 2012-03-27 18:37:11

+0

+1为一种新方法! – bernie 2012-03-27 18:37:38

1

正则表达式是在这种特殊情况下可能矫枉过正。
不过这里的另一个选项:

import re 
soup.find_all('a', id=re.compile(r'[dgrdAcquired_hyplnkacquired_]\d+')) 

请注意s/find_all/findAll/g如果使用BS3。
结果(用于显示的目的而被取下有点空白):

[<a href="InstitutionProfile.aspx?parID_RSSD=3557617&amp;parDT_END=20110429" 
    id="dgrdAcquired_hyplnkacquired_0">FIRST CHOICE COMMUNITY BANK (3557617)</a>, 
<a href="InstitutionProfile.aspx?parID_RSSD=104038&amp;parDT_END=20110429" 
    id="dgrdAcquired_hyplnkacquired_1">PARK AVENUE BANK, THE (104038)</a>]