Skip to main content
 首页 » 编程设计

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

2024年10月24日11开发

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

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 行。我尝试将它们添加到列表中,然后删除不需要但不成功的。

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

非常感谢。

请您参考如下方法:

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