2009-06-14 55 views
1

所以我之前問過一個關於從html頁面獲取高分的問題,另一個用戶給了我下面的代碼來幫助。我是python和beautifulsoup的新手,所以我正在嘗試通過其他一些代碼一塊一塊地去做。據我所知大部分,但我不明白這是什麼一段代碼是什麼,它的功能是:在Python中涉及urllib2和BeautifulSoup的這個函數是什麼?

def parse_string(el): 
     text = ''.join(el.findAll(text=True)) 
     return text.strip() 

這裏是整個代碼:在一個元素內部

from urllib2 import urlopen 
from BeautifulSoup import BeautifulSoup 
import sys 

URL = "http://hiscore.runescape.com/hiscorepersonal.ws?user1=" + sys.argv[1] 

# Grab page html, create BeatifulSoup object 
html = urlopen(URL).read() 
soup = BeautifulSoup(html) 

# Grab the <table id="mini_player"> element 
scores = soup.find('table', {'id':'mini_player'}) 

# Get a list of all the <tr>s in the table, skip the header row 
rows = scores.findAll('tr')[1:] 

# Helper function to return concatenation of all character data in an element 
def parse_string(el): 
    text = ''.join(el.findAll(text=True)) 
    return text.strip() 

for row in rows: 

    # Get all the text from the <td>s 
    data = map(parse_string, row.findAll('td')) 

    # Skip the first td, which is an image 
    data = data[1:] 

    # Do something with the data... 
    print data 

回答

3

el.findAll(text=True)返回所有文字及其子元素。通過文本我的意思是一切都不在標籤內;所以在<b>hello</b>然後「你好」將是文字,但<b></b>不會。

因此,該函數將給定元素下方的所有文本連接在一起,並從正面和背面剝離空白。

這裏給findAll文檔的鏈接:http://www.crummy.com/software/BeautifulSoup/documentation.html#arg-text

+0

使用反引號的HTML。 :) – 2009-06-14 02:18:33

相關問題