如何获取包含特定文本

时间:2015-10-09 13:38:08

标签: python html beautifulsoup

我想从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

这两个解决方案适用于“抽象”和“关键字”部分,但它不适用于“引用”这个词,我不明白,因为这个词也封装在span标签中:

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

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

1 个答案:

答案 0 :(得分:1)

我认为只是在“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

请注意,您可以通过在文本和输出字典键之间进行映射来简化代码并使其更加pythonic:

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

我们还可以简化代码的“元素定位”部分,但是,至少不知道问题的上下文和所需的输出,这里很难提供帮助。

相关问题