2016-03-07 41 views
0

从这个代码:正则表达式/ beautifulsoup如何从html表中提取列的所有值?

<tr><td>PC1</td><td>zz:zz:zz:zz:zz:ce</td><td>10.0.0.244</td><td>23 hours, 55 minutes, 25 seconds</td></tr> 
<tr><td>PC2</td><td>zz:zz:zz:zz:zz:cf</td><td>10.0.0.245</td><td>23 hours, 23 minutes, 27 seconds</td></tr> 

我想获得MAC地址的数组和另一个数组IP的

我觉得那样的东西正则表达式的Mac电脑:<\/td><td>(.*?){17}<\/td> 但它的运行时间相匹配太。

有什么建议吗?

谢谢!

+0

由于您已经知道mac地址位于第二列,因此使用xpath查询使用lxml(比美丽的汤快)。你不需要正则表达式。 –

+1

可能的重复http://stackoverflow.com/questions/13074586/extracting-selected-columns-from-a-table-using-beautifulsoup – maazza

回答

2

html你给,你可以做到以下几点:

from bs4 import BeautifulSoup 

html = """<tr><td>PC1</td><td>zz:zz:zz:zz:zz:ce</td><td>10.0.0.244</td><td>23 hours, 55 minutes, 25 seconds</td></tr> 
<tr><td>PC2</td><td>zz:zz:zz:zz:zz:cf</td><td>10.0.0.245</td><td>23 hours, 23 minutes, 27 seconds</td></tr>""" 

soup = BeautifulSoup(html) 
mac_ips = [] 

for tr in soup.find_all('tr'): 
    cols = [td.text for td in tr.find_all('td')] 
    mac_ips.append((cols[1], cols[2])) 

for mac, ip in mac_ips: 
    print '{} {}'.format(mac, ip) 

给你:

zz:zz:zz:zz:zz:ce 10.0.0.244 
zz:zz:zz:zz:zz:cf 10.0.0.245 

mac_ips将持有的每一行作为一个匹配对:

[(u'zz:zz:zz:zz:zz:ce', u'10.0.0.244'), (u'zz:zz:zz:zz:zz:cf', u'10.0.0.245')] 

如果你想单独列出,那么你可以做到以下几点:

from bs4 import BeautifulSoup 

html = """<tr><td>PC1</td><td>zz:zz:zz:zz:zz:ce</td><td>10.0.0.244</td><td>23 hours, 55 minutes, 25 seconds</td></tr> 
<tr><td>PC2</td><td>zz:zz:zz:zz:zz:cf</td><td>10.0.0.245</td><td>23 hours, 23 minutes, 27 seconds</td></tr>""" 

soup = BeautifulSoup(html) 
mac = [] 
ip = [] 

for tr in soup.find_all('tr'): 
    cols = [td.text for td in tr.find_all('td')] 
    mac.append(cols[1]) 
    ip.append(cols[2]) 

print mac 
print ip 

给你:

[u'zz:zz:zz:zz:zz:ce', u'zz:zz:zz:zz:zz:cf'] 
[u'10.0.0.244', u'10.0.0.245'] 

注:如果您解析更多的HTML,那么你可能还需要先找到封闭<table>

-2
try: 
    table = soup.find('table') 
except AttributeError as e: 
    print 'No tables found, exiting' 
    return 1 

# Get rows 
try: 
    rows = table.find_all('tr') 
except AttributeError as e: 
    print 'No table rows found, exiting' 
    return 1 
+0

请添加一些关于您的解决方案的意见,为什么以及如何解决问题 –