【问题标题】:Does BeautifulSoup find_all() preserve tag order?BeautifulSoup find_all() 是否保留标签顺序?
【发布时间】:2016-02-12 19:07:57
【问题描述】:

我希望使用 BeautifulSoup 来解析一些 HMTL。我有一个有几行的表。我正在尝试找到满足某些条件(某些属性值)的行,并稍后在我的代码中使用该行的索引。

问题是:find_all() 是否保留了我的行在它返回的结果集中的顺序?

我在docs 中没有找到这个,谷歌搜索只找到了this answer

'BeautifulSoup 标签不会跟踪它们在页面中的顺序,不会。'

但他没有说他从哪里得到这些信息。

我会很高兴得到答案,但更高兴的是指向一些解释这一点的文档的指针。

编辑:dstudeba 使用 next_sibling 为我指明了这个“解决方法”的方向。

from bs4 import BeautifulSoup
soup = BeautifulSoup(open('./mytable.html'), 'html.parser')
row = soup.find('tr', {'class':'something', 'someattr':'somevalue'})
myvalues = []
while True:
    cell = row.find('td', {'someattr':'cellspecificvalue'})
    myvalues.append(cell.get_text())
    row = row.find_next_sibling('tr', {'class':'something', 'someattr':'somevalue'})
    if not row:
        break

这会按照它们在我的 html 文件中出现的顺序获取我需要的单元格内容。

但是我仍然想知道在 BeautifulSoup 文档中我可以找到 find_all() 是否保留顺序。这就是为什么我不接受 dstudeba 的回答。 (我的赞成票没有显示,还没有足够的代表:P)

【问题讨论】:

    标签: python python-2.7 beautifulsoup


    【解决方案1】:

    根据我的经验,find_all 确实保持秩序。但是,要确保您可以使用 find_all_next 方法,该方法使用将保留订单的 find_next 方法。 Here is a link 文档。

    【讨论】:

    • 很抱歉没有尽快回复您。我读到了 find_next,只是没有完全理解(不是以英语为母语的人)。我试试看!
    猜你喜欢
    • 1970-01-01
    • 2019-11-25
    • 2021-01-22
    • 2017-03-13
    • 2010-10-14
    • 2017-03-04
    • 1970-01-01
    • 2011-02-28
    • 2015-02-24
    相关资源
    最近更新 更多