Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/328.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python BeautifulSoup如何索引标记对象_Python_Object_Indexing_Beautifulsoup_Tags - Fatal编程技术网

Python BeautifulSoup如何索引标记对象

Python BeautifulSoup如何索引标记对象,python,object,indexing,beautifulsoup,tags,Python,Object,Indexing,Beautifulsoup,Tags,我有以下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="ri

我有以下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>
我得到这个错误:

  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
文件“test.py”,第45行,在
a=tr[2]。查找('td')
文件“C:\Python27\lib\site packages\bs4\element.py”,第1011行,在\uuu getitem中__
返回self.attrs[键]
关键错误: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 = 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对象不是数组或任何类型的集合,它是一个漂亮的soup标记对象。错误表明[2]不是对tr对象执行的有效操作。

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


此时,tr对象不是数组或任何类型的集合,它是一个漂亮的soup标记对象。错误表明[2]不是对tr对象执行的有效操作。

有道理!谢谢你花时间解释,宝拉,代码有效,我明白了!有道理!谢谢你花时间解释,宝拉,代码有效,我明白了!