簡體   English   中英

使用 Beautifulsoup 導航表格時遇到問題

[英]Having trouble with navigating tables using Beautifulsoup

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

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


containers = page_soup.findAll("table", {"class":"stats"})
container = containers[0]
rows = container.findChildren(['td'])

我只得到第一行文本,但我想要第二行,它似乎無法正常工作......請幫助並感謝!

如果你使用[0]那么你只會得到第一個元素。 要獲得第二個元素,請使用[1]

或使用for -loop 處理所有元素


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>]
-

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM