如何在python中的两个不同标签之间提取html?

时间:2013-11-12 16:25:30

标签: python html-parsing

我有以下html:

<h2>blah</h2>
html content to extract 
(here can come tags, nested structures too, but no top-level h2)
<h2>other blah</h2>

我可以在python中不使用string.split("<h2>")来提取内容吗? (说,使用BeautifulSoup或其他库?)

3 个答案:

答案 0 :(得分:1)

使用BeautifulSoup,使用.next_siblings iterable来获取标记后的文本:

>>> from bs4 import BeautifulSoup, NavigableString
>>> from itertools import takewhile
>>> sample = '<h2>blah</h2>\nhtml content to extract\n<h2>other blah<h2>'
>>> soup = BeautifulSoup(sample)
>>> print ''.join(takewhile(lambda e: isinstance(e, NavigableString), soup.h2.next_siblings))

html content to extract

这将查找soup.h2元素后面的所有文本元素,并将它们连接成一个字符串。

答案 1 :(得分:1)

以下是使用http://htql.net中的HTQL的一些测试代码:

sample="""<h2>blah</h2>
        html content to extract 
        <div>test</div>
        <h2>other blah<h2>
    """

import htql
htql.query(sample, "<h2 sep excl>2")
# [('\n        html content to extract \n        <div>test</div>\n        ',)]

htql.query(sample, "<h2 sep> {a=<h2>:tx; b=<h2 sep excl>2 | a='blah'} ")
# [('blah', '\n        html content to extract \n        <div>test</div>\n        ')]

答案 2 :(得分:0)

让我分享一些更强大的解决方案:

def get_chunk_after_tag(tag):
    """ tag is a tag element in a bs4 soup.
    """
    result = ''
    for elem in tag.next_siblings:
        if isinstance(elem, bs4.Tag) and elem.name == tag.name:
            break
        result += str(elem)
    return result

用于从<hX>提取文本到<hX>。可以轻松修改它以将标签中的文本提取到另一个标签。

相关问题