如何获取包含特定文本的 <span> 标签的 parent

how to get a parent of an <span> tag containing a specific text

我想识别 html 文件中的某些部分,每个部分都封装在 div 中。要查找该部分,标题通常封装在 span 标记中。

所以我尝试了这两种解决方案:

1)

doc_html = BeautifulSoup(doc_html, 'html.parser')
my_file['div'] = doc_html.find_all('div')
for div in my_file['div'] :
    for span in div.find_all('span'):
        if span.text == 'ABSTRACT':
            my_file['Abstract'] = div
        if span.text == 'Keywords':
            my_file['Keywords'] = div
        if span.text == 'REFERENCES':
            my_file['References'] = div

2)

for span in doc_html.find_all('span'):
    if span.string == 'ABSTRACT':
        my_file['Abstract'] = span.parent
    if span.string == 'Keywords':
        my_file['Keywords'] = span.parent
    if span.string == 'REFERENCES':
        my_file['References'] = span.parent

这两个解决方案适用于 'abstract' 和 'keywords' 部分,但不适用于 'references' 这个词,我不明白,因为这个词也被封装了在跨度标签中:

<span style="font-family: Times New Roman,Bold; font-size:10px">REFERENCES 
<br/></span>

最后我想知道是否有一种优化此代码的方法,例如将其放在一行中

我觉得只是"REFERENCES"后面多了一个换行符,去掉:

text = span.get_text(strip=True)
if text == 'ABSTRACT':
    my_file['Abstract'] = div
if text == 'Keywords':
    my_file['Keywords'] = div
if text == 'REFERENCES':
    my_file['References'] = div

请注意,您可以通过在文本和输出字典键之间建立映射来简化代码并使其更符合 Python 风格:

mapping = {'ABSTRACT': 'Abstract', 'Keywords': 'Keywords', 'REFERENCES': 'References'}
for div in my_file['div'] :
    for span in div.find_all('span'):
        text = span.get_text(strip=True)

        if text in mapping:
            my_file[mapping[text]] = div

我们也可以简化代码的 "element locating" 部分,但是,如果至少不知道问题的上下文和所需的输出,就很难在此处提供帮助。