擅长:python、mysql、java
<p>当前接受的答案适用于所有城市,而问题只需要第一个。</p>
<p>如果只需要第一个子元素,可以利用<code>.children</code>返回迭代器而不是列表。请记住,迭代器会动态地生成列表项,并且由于我们只需要迭代器的第一个元素,因此我们不需要生成所有其他city元素(从而节省时间)。</p>
<pre><code>for div in nsoup.find_all(class_='cities'):
first_child = next(div.children, None)
if first_child is not None:
print(first_child.string.strip())
</code></pre>