2013-01-10 40 views
0

我正在學習Python並使用BeautifulSoup來爬取一些網頁。我期望做的是找到第一個'td'的孩子'a',提取href並將其添加到列表中。如何以及在哪裏可以將href添加到單元格文本中?提取孩子href到BeautifulSoup列表

import urllib2 

from BeautifulSoup import BeautifulSoup 

def listify(table): 
    """Convert an html table to a nested list""" 
    result = [] 
    rows = table.findAll('tr') 
    for row in rows: 
     result.append([]) 
     cols = row.findAll('td') 
     for col in cols: 
      strings = [_string.encode('utf8') for _string in col.findAll(text=True)] 
      text = ''.join(strings) 
      result[-1].append(text) 
    return result 
+0

'的cols [1] .find( 'A') 'href' 屬性]'應該做的伎倆 – root

+1

不使用BeautifulSoup 4,而不是任何理由3? –

+0

良好的拜訪bs4。我下載了兩個,但安裝了3.現在使用4。 – user1645914

回答

1
  • 找到的第一個td:使用row.find('td')代替;它會返回第一場比賽
  • 找到孩子a,再次使用.find('a')找到第一個。
  • 元素就像一個python dict,使用item獲取元素屬性,如href

在一起,使得:

cell = row.find('td') 
link = cell.find('a') if cell else None 
if link is not None and 'href' in link: 
    result[-1].append(link['href'])