Python + BS从网页表中挑选特定的单词(位置)

时间:2015-06-12 04:36:56

标签: python beautifulsoup

大家好......我想从网页上的表格中选择一个特定位置的单词。源代码如下:

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>

'''

我想在这里选择颜色词(可能是“白色”,“红色”或其他东西)。我试过的是:

soup = BeautifulSoup(table)

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

它给出了:

Color:
 
White

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

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

非常感谢。

1 个答案:

答案 0 :(得分:2)

这将匹配'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']]

只返回颜色本身,做...

# 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']