<p>马尔金·皮耶特的回答将使它真正起作用。我有过嵌套<code>table</code>标记的一些经验,当我只是简单地获得列表中的第二个表而没有注意时,它就破坏了我的代码。</p>
<p>当您尝试<code>find_all</code>并获取第n个元素时,可能会出现混乱,您最好找到所需的第一个元素,并确保第n个元素实际上是该元素的同级而不是子元素。</p>
<ol>
<li>您可以使用<code>find_next_sibling()</code>来保护您的代码</li>
<li>您可以先找到父项,然后使用find_all(recursive=False)来保证搜索范围。</li>
</ol>
<p>以防万一。我将在下面列出我的代码(使用recursive=FALSE)。</p>
<pre><code>import urllib2
from bs4 import BeautifulSoup
text = """
<html>
<head>
</head>
<body>
<table>
<p>Table1</p>
<table>
<p>Extra Table</p>
</table>
</table>
<table>
<p>Table2</p>
</table>
</body>
</html>
"""
soup = BeautifulSoup(text)
tables = soup.find('body').find_all('table')
print len(tables)
print tables[1].text.strip()
#3
#Extra Table # which is not the table you want without warning
tables = soup.find('body').find_all('table', recursive=False)
print len(tables)
print tables[1].text.strip()
#2
#Table2 # your desired output
</code></pre>