繁体   English   中英

BeautifulSoup如何索引标签对象

[英]BeautifulSoup how to index tag object

我有这个html代码:

<tr class="even">
  <td style="background: #8FB9B0; color: #8FB9B0;">0&#160;</td>
  <td>Plupp</td>
  <td class="right">RIFLEMAN</td>
  <td class="right">139</td>
  <td class="right">6</td>
  <td class="right">30</td>
  <td class="right" title="Packet loss: ">64</td>
  <td class="center">No</td>
  <td class="center">No</td>
  <td class="center">Yes</td>

这是“偶数”类的第二个tr。 我想从这里提取第二个TD aka Plupp和第三个aka RIFLEMAN

请帮助我了解我在做什么错,这是我的代码:

tr = soup.find_all('tr', class_='even')[1]
a = tr[2].find('td')

我收到此错误:

  File "test.py", line 45, in <module>
    a = tr[2].find('td')
  File "C:\Python27\lib\site-packages\bs4\element.py", line 1011, in __getitem__
    return self.attrs[key]
KeyError: 2

您的问题始于:

tr = soup.find_all('tr', class_='even')[1]

该行末尾的[1]表示返回的内容是单个标签而不是标签列表,但在下一行中:

a = tr[2].find('td')

您尝试为没有索引的对象建立索引,我是否建议实现目标的方法是将这一行替换为:

tds = tr.find_all("td") # returns a list of td's within the tr
a = tds[2] # accesses RIFLEMAN
b = tds[1] # accesses Pupp.

第一行返回一个数组,其中包含所有带有类属性“偶数”的tr标记。 [1]数组索引选择器表示选择数组中的第二个tr标签(记住数组从0开始)。

在这一点上,tr对象不是一个数组或要使用方括号的任何集合,它是一个漂亮的汤标签对象。 错误是说[2]不是要在tr对象上执行的有效操作。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM