BeautifulSoup:查找第n次出现的元素

BeautifulSoup: Find n-th occurence of element

我的 html 文件看起来像

<li class="fn" id="fn-8">
    <p id="p-53"> Some text
    </p>
</li>
<li class="fn" id="fn-10">
    <p id="p-63"> Some more text
    </p>
</li>

等等。脚注元素的数量各不相同,id 不可靠。但是,我只对倒数第二个脚注感兴趣。我知道我可以使用

获取脚注元素的数量
number_of_footnotes = len(soup.find_all("li", {"class":"fn"}))

而且我可以遍历所有事件。但是有没有更pythonic的方法来精确提取一个元素?

使用切片获取列表中的项目。

last_item = soup.find_all("li", {"class":"fn"})[-1]

下一刻我意识到 soup.find_all("li", {"class":"fn"}) returns 一个列表。因此,

list_of_footnotes = soup.find_all("li", {"class":"fn"})
number_of_footnotes = len(soup.find_all("li", {"class":"fn"}))
next_to_last_footnote = list_of_footnotes[number_of_footnotes - 2]

正好是我的倒数第二个脚注。

-2 而不是 -1 以纠正 Python 以 0 开头的事实。