【问题标题】:BeautifulSoup get all the values of a particular columnBeautifulSoup 获取特定列的所有值
【发布时间】:2014-01-30 21:35:51
【问题描述】:

我正在使用 BeautifulSoup 来解析 html。到目前为止,我有以下代码:

url = "http://routerpasswords.com"
data = {"findpass":"1", "router":"Belkin", "findpassword":"Find Password"}
post_data = urllib.urlencode(data)
req = urllib2.urlopen(url, post_data)
html_str = req.read()
parser = new BeautifulSoup(html_str)
table = parser.find("table")

有没有办法获得column 下所有 cel 的列表? 这是一个例子: 如果我有这张桌子:

<table cellpadding="0" cellspacing="0" width="100%">
<thead>
<tr>
<th>Manufacturer</th>
<th>Model</th>
<th width="80">Protocol</th>
<th width="80">Username</th>
<th width="80">Password</th>
</tr>
</thead>
<tbody>
<tr>
<td><b>BELKIN</b></td>
<td>F5D6130</td>
<td>SNMP</td>
<td>(none)</td>
<td>MiniAP</td>
</tr>
<tr>
<td><b>BELKIN</b></td>
<td>F5D7150<i> Rev. FB</i></td>
<td>MULTI</td>
<td>n/a</td>
<td>admin</td>
</tr>
<tr>
<td><b>BELKIN</b></td>
<td>F5D8233-4</td>
<td>HTTP</td>
<td>(blank)</td>
<td>(blank)</td>
</tr>
<tr>
<td><b>BELKIN</b></td>
<td>F5D7231</td>
<td>HTTP</td>
<td>admin</td>
<td>(blank)</td>
</tr>
</tbody>
</table>

如何获得Username 列中所有项目的列表?我希望它们也是字符串。

【问题讨论】:

  • 你的 html 看起来怎么样?
  • 一秒钟我会发布它。
  • 对不起,我之前可能不太清楚。我编辑了我的问题。

标签: python html python-2.7 html-parsing beautifulsoup


【解决方案1】:
from BeautifulSoup import BeautifulSoup
soup = BeautifulSoup(open("file.html",'r').read())
cols = [header.string for header in soup.find('thead').findAll('th')]
col_idx = cols.index('Username')
col_values = [td[col_idx].string 
              for td in [tr.findAll('td') 
                         for tr in soup.find('tbody').findAll('tr')]]
print(col_values)

结果:

[u'(none)', u'n/a', u'(空白)', u'admin']

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-14
    • 2018-10-07
    • 2021-03-31
    • 2011-01-01
    • 2023-03-21
    • 1970-01-01
    相关资源
    最近更新 更多