2009-12-02 35 views
2

分裂一個帶有鏈接的逗號分隔的列表我有一個逗號在HTML文檔中的表格單元格分隔列表,但一些在列表中的項目鏈接:與beautifulsoup

<table> 
    <tr> 
    <td>Names</td> 
    <td>Fred, John, Barry, <a href="http://www.example.com/">Roger</a>, James</td> 
    </tr> 
</table> 

我已經用美麗的湯解析HTML是,而且我可以得到表中,但什麼是最好的方式來分割它,大致返回的數據結構,如:

[ 
    {'name':'Fred'}, 
    {'name':'John'}, 
    {'name':'Barry'}, 
    {'name':'Roger', 'url':'http://www.example.com/'}, 
    {'name':'James'}, 
] 

回答

10

這是你可以做的一種方式:

import BeautifulSoup 

soup = BeautifulSoup.BeautifulSoup('''<table> 
    <tr> 
    <td>Names</td> 
    <td>Fred, John, Barry, <a href="http://www.example.com/">Roger</a>, James</td> 
    </tr> 
</table>''') 

result = [] 
for tag in soup.table.findAll('td')[1]: 
    if isinstance(tag, BeautifulSoup.NavigableString): 
    for name in tag.string.split(','): 
     name = name.strip() 
     if name: 
     result.append({ 'name': name }) 
    else: 
    result.append({ 'name': tag.string.strip(), 'url': tag["href"] }) 

print result 
+0

+1不錯的解決方案 – vikingosegundo

+0

+1其實真的很酷 – atv

+0

確實不錯! 小記:我會用「isinstance(tag,BeautifulSoup.NavigableString)」替換「type(tag)是BeautifulSoup.NavigableString」。 – taleinat