如何使用递归在BeautifulSoup中进行刮边?

2024-09-29 18:45:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用下面的代码来刮取一个xml文件,这些代码工作得非常好fine:- 你知道吗

    f = open("sample_data.xml", "r")
    contents = f.read()
    soup = BeautifulSoup(contents, features="xml")
    for component in soup.find_all("component"):
        for section in component.find_all("section"):
            for entry in section.find_all("entry"):
                for encounter in entry.find_all("encounter"):
                    for participant in encounter.find_all("participant"):
                        for participantRole in participant.find_all("participantRole"):
                            for playingEntity in participantRole.find_all("playingEntity"):
                                for name in playingEntity.find_all("name"):
                                    print(name.text)

但是我想把它放在一个递归中,而不是使用这么多for循环。为此,我创建了一个列表,作为遍历路径来查找所需的元素,如below:- 你知道吗

traversal_path = ['component', 'section', 'entry', 'encounter', 'participant', 'participantRole', 'playingEntity', 'name']

作为递归函数的断点,我们可以使用遍历路径的最后一项,在我们的例子中是name。当我们继续遍历traversal_path时,列表中的第一项被删除,直到只剩下最后一项。根据这一点,现在我的职能变成了this:- 你知道吗

f = open("sample_data.xml", "r")
contents = f.read()
soup = BeautifulSoup(contents, features="xml")
traversal_path = ['component', 'section', 'entry', 'encounter', 'participant', 'participantRole', 'playingEntity', 'name']

def rec(traversal_path, soup):
    print(traversal_path)
    if len(traversal_path) == 1:
        for last_item in soup.find_all(traversal_path[0]):
            print(last_item.text)
    else:
        t = traversal_path.pop(0)
        for first_item in soup.find_all(t):
            return rec(traversal_path, first_item)

rec(traversal_path, soup)

我得到的输出就是遍历路径,就像below:- 你知道吗

['component', 'section', 'entry', 'encounter', 'participant', 'participantRole', 'playingEntity', 'name']
['section', 'entry', 'encounter', 'participant', 'participantRole', 'playingEntity', 'name']
['entry', 'encounter', 'participant', 'participantRole', 'playingEntity', 'name']
['encounter', 'participant', 'participantRole', 'playingEntity', 'name']

当我打印soup而不是traversal_path时,我得到的输出仅打印到entry

另外,我的函数中的问题似乎出现在else部分,它没有进入递归。在这件事上的任何帮助都是非常感谢的


Tags: pathnameinforsectionallfindcomponent
1条回答
网友
1楼 · 发布于 2024-09-29 18:45:45
 def rec(traversal_path, soup):
    if len(traversal_path) == 1:
        for last_item in soup.find_all(traversal_path[0]):
            print(last_item.text)
    else:
         try:
            for first_item in soup.find_all(traversal_path[0]):
                rec(traversal_path, first_item)
            t = traversal_path.pop(0)
        except Exception as e:
            pass

rec(field['traversal_path'].split(" "), soup)

只需删除return语句并处理异常

相关问题 更多 >

    热门问题