Python 使用Beautifulsoup导航表时遇到问题 不是这个 我想要这个 containers=page_soup.findAll(“表”,{“类”:“stats”}) 容器=容器[0] rows=container.findChildren(['td'])

Python 使用Beautifulsoup导航表时遇到问题 不是这个 我想要这个 containers=page_soup.findAll(“表”,{“类”:“stats”}) 容器=容器[0] rows=container.findChildren(['td']),python,beautifulsoup,Python,Beautifulsoup,我只得到第一行文本,但我想要第二行,它似乎工作不正常。。。请帮忙,谢谢 如果使用[0]则只会得到第一个元素。要获取第二个元素,请使用[1] 或者使用for-循环处理所有元素 text='' 不是这个 我想要这个 ''' 从bs4导入BeautifulSoup作为BS soup=BS(文本“html.parser”) containers=soup.findAll(“表”,{“类”:“stats”}) 容器=容器[0] rows=container.findChildren(['td']) 打印

我只得到第一行文本,但我想要第二行,它似乎工作不正常。。。请帮忙,谢谢

如果使用
[0]
则只会得到第一个元素。要获取第二个元素,请使用
[1]

或者使用
for
-循环处理所有元素


text=''
不是这个
我想要这个
'''
从bs4导入BeautifulSoup作为BS
soup=BS(文本“html.parser”)
containers=soup.findAll(“表”,{“类”:“stats”})
容器=容器[0]
rows=container.findChildren(['td'])
打印('1:',行)
容器=容器[1]
rows=container.findChildren(['td'])
打印('2:',行)
打印('---用于循环--')
对于集装箱中的集装箱:
打印(container.findChildren(['td']))
打印('-')
结果

text = '''<div class ="table">
   <table class="stats">
      <td>Not this</td>
   </table>

   <table class="stats">
      <td>I want this</td>
   </table>
</div>'''


from bs4 import BeautifulSoup as BS

soup = BS(text, 'html.parser')
containers = soup.findAll("table", {"class":"stats"})

container = containers[0]
rows = container.findChildren(['td'])
print('1st:', rows)

container = containers[1]
rows = container.findChildren(['td'])
print('2nd:', rows)

print('--- for-loop ---')
for container in containers:
    print(container.findChildren(['td']))
    print('-')
1st:[不是这个]
第二名:[我想要这个]
---for循环---
[不是这个]
-
[我想要这个]
-

如果使用
[0]
则只得到一个元素。使用
[1]
获取第二个元素。或us
for
-循环使用容器中的行的所有元素
:cells=row.findAll('td')
您在答案
容器[1]
中找到了第二个元素。谢谢您,这真的很有帮助!!!!我在看盒子外面而不是里面啊哈
text = '''<div class ="table">
   <table class="stats">
      <td>Not this</td>
   </table>

   <table class="stats">
      <td>I want this</td>
   </table>
</div>'''


from bs4 import BeautifulSoup as BS

soup = BS(text, 'html.parser')
containers = soup.findAll("table", {"class":"stats"})

container = containers[0]
rows = container.findChildren(['td'])
print('1st:', rows)

container = containers[1]
rows = container.findChildren(['td'])
print('2nd:', rows)

print('--- for-loop ---')
for container in containers:
    print(container.findChildren(['td']))
    print('-')
1st: [<td>Not this</td>]
2nd: [<td>I want this</td>]
--- for-loop ---
[<td>Not this</td>]
-
[<td>I want this</td>]
-