【问题标题】:regex/beautifulsoup how to extract the all values of column from html table?regex/beautifulsoup 如何从 html 表中提取列的所有值?
【发布时间】:2016-06-20 17:58:46
【问题描述】:

从此代码:

<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 的正则表达式:&lt;\/td&gt;&lt;td&gt;(.*?){17}&lt;\/td&gt; 但它也符合正常运行时间。

有什么建议吗?

谢谢!

【问题讨论】:

标签: python html regex beautifulsoup


【解决方案1】:
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

【讨论】:

  • 请添加一些关于您的解决方案的 cmet,说明它为什么以及如何解决问题
【解决方案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,那么你可能还需要先找到封闭的&lt;table&gt;

【讨论】:

    猜你喜欢
    • 2017-03-11
    • 1970-01-01
    • 2011-07-16
    • 2021-09-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多