Python + BS 从网页中选择一个特定的词(位置) table

Python + BS Picking a specific word(location) form webpage table

大家好…我想从网页上的 table 中选择一个关于特定位置的词。源代码如下:

table = '''
<TABLE class=form border=0 cellSpacing=1 cellPadding=2 width=500>
<TBODY>
<TR>
<TD vAlign=top colSpan=3><IMG class=ad src="/images/ad.gif" width=1     height=1></TD></TR>
<TR>
<TH vAlign=top width=22>Code:</TH>
<TD class=dash vAlign=top width=5 lign="left">&nbsp;</TD>
<TD class=dash vAlign=top width=30 align=left><B>BAN</B></TD></TR>
<TR>
<TH vAlign=top>Color:</TH>
<TD class=dash vAlign=top align=left>&nbsp;</TD>
<TD class=dash vAlign=top align=left>White</TD></TR>
<TR>
<TD colSpan=3>&nbsp;</TD></TR></TBODY></TABLE>

'''

我想在这里选择颜色这个词(可以是“白色”,"red" 或其他)。我试过的是:

soup = BeautifulSoup(table)

for a in soup.find_all('table')[0].find_all('tr')[2:3]:
    print a.text

它给出:

Color:
 
White

看起来像 4 行。我尝试将它们添加到列表中,然后删除不需要但不成功的。

只在 table 中选择颜色的最佳方法是什么?

非常感谢。

这将匹配 'white' 大小写无关的所有实例 ...

soup = BeautifulSoup(table)

res = []
for a in soup.find_all('table')[0].find_all('tr')[2:3]:
    if 'white' in a.text.lower():
        text = a.text.encode('ascii', 'ignore').replace(':','').split()
        res.append(text)

稍微好一点的实现...

# this will iterate through all 'table' and 'tr' tags within each 'table'
res = [tr.text.encode('ascii', 'ignore').replace(':','').split() \
        for table in soup.findAll('table') for tr in table.findAll('tr') \
        if 'color' in tr.text.lower()]

print res
[['Color', 'White']]

只有 return 颜色本身,做...

# Assuming the same format throughout the html
# if format is changing just add more logic
tr.text.encode('ascii', 'ignore').replace(':','').split()[1]
...
print res
['White']