这个功能在涉及Urllib2和Beautifulsoup的Python中做什么?
题
因此,我早些时候询问了一个关于检索高分的问题,形成了HTML页面,另一个用户给了我以下代码以提供帮助。我是Python和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
解决方案
el.findAll(text=True)
返回元素及其子元素中包含的所有文本。通过文字,我的意思是所有不在标签中的东西;所以 <b>hello</b>
然后“你好”是文字,但是 <b>
和 </b>
不会。
因此,该功能将所有文本在给定元素下面发现,并从前后脱离空格。
这是指向 findAll
文档: http://www.crummy.com/software/beautifulsoup/documentation.html#arg-text
不隶属于 StackOverflow