【问题标题】:How to go about identifying nodes in an HTML tree that are semantically related but not structurally如何识别 HTML 树中语义相关但结构不相关的节点
【发布时间】:2017-01-28 23:28:49
【问题描述】:

我面临以下问题,因为维基词典上的 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>]

但只有一个项目属于英语部分。其他属于葡萄牙语和沃拉普克语。然而,标记英语部分的跨度 (<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

【问题讨论】:

    标签: python html beautifulsoup html-parsing


    【解决方案1】:

    由于 HTML 中没有结构,并且这些部分是扁平的并且缺乏 DOM 层次结构,因此一种选择是选择“English”标题,然后遍历所有下一个同级元素,直到遇到另一个 h2 元素包含.mw-headline 标头。

    这样做,您实际上是在选择“英语”部分中的所有同级元素。

    从那里,您可以选择所有所需的.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()
    

    【讨论】: