如何着手识别 HTML 树中语义相关但结构不相关的节点

How to go about identifying nodes in an HTML tree that are semantically related but not structurally

我遇到了以下问题,因为维基词典上的 HTML 似乎是以一种方式布局的,其中各个语言的部分实际上并不是支配相应部分条目的节点。我只想从某些特定语言的部分获取数据,比如英语。我可能感兴趣的数据是例如跨度 "IPA" : <span class="IPA" lang="">/dɒɡ/</span>,但是这个跨度出现了几次:

[<span class="IPA" lang="">/dɒɡ/</span>, <span class="IPA" lang="">/dɔɡ/</span>, <span class="IPA" lang="">/dɑɡ/</span>, <span class="IPA" lang="">-ɒɡ</span>, <span class="IPA" lang="">/ˈdɔɡ/</span>, <span class="IPA" lang="">/ˈdɔ.ɡi/</span>, <span class="IPA" lang="">[doɡ]</span>]

但只有一项属于英语部分。其他属于葡萄牙语和 Volapük。然而,标记英语部分 (<span class="mw-headline" id="English">English</span>) 的跨度不是 IPA-span 节点的前导节点,因此不清楚如何根据 HTML 解析来收集正确的数据,因为到目前为止我一直在尝试:

from bs4 import BeautifulSoup
import requests
from sys import argv

def find_IPA(
    r = requests.get('https://en.wiktionary.org/wiki/'+word)
    content = r.content
    soup = BeautifulSoup(content.decode('utf-8','ignore'),'lxml')
    print (soup.findAll('span', {'class' : "IPA"}))


if __name__ == '__main__':
    try:
        find_IPA(argv[1])
    except Exception as e:
        print(format(e))

那么,有没有更好的方法来处理 HTML 文件中语义相关性与结构相关性脱节的情况?

(示例位来自此页面> https://en.wiktionary.org/wiki/dog

由于 HTML 中没有结构并且部分是扁平的并且缺少 DOM 层次结构,因此一种选择是 select 'English' header 然后迭代所有下一个兄弟元素,直到遇到另一个包含 .mw-headline header.

h2 元素

这样做实际上是 selecting 'English' 部分中的所有同级元素。

从那里,您可以 select 所有需要的 .IPA 元素。

english_header = soup.find('span', {'id': 'English', 'class': 'mw-headline'})

if english_header:
    next_sibling = english_header.parent.find_next_sibling()

    while next_sibling and not (next_sibling.name == 'h2' and next_sibling.select('.mw-headline')):
        for element in next_sibling.select('.IPA'):
            print(element)

        next_sibling = next_sibling.find_next_sibling()