BeautifulSoup:获取标签文本到特定标签

时间:2018-05-29 06:55:24

标签: python beautifulsoup scrape

我想在HTML页面上显示所有显示的文本,直到达到某个标记。例如,我想在页面上显示所有显示的文本,直到标记为id" end_content"被打了。

有没有办法用BeautifulSoup做到这一点? 这与soup.get_text()方法类似,不同之处在于它会在遇到id为#34; end_content"的标记后停止提取文本。

1 个答案:

答案 0 :(得分:2)

我会做以下事情:

html = (
    '<h1>HEY!</h1>'
    '<div>'
        'How are'
        '<h2>you?</h2>'
        '<div id="end_content">END</div>'
    '</div>'
    'Some other text'
)

soup = BeautifulSoup(html, 'lxml')
>>> soup.select_one('#end_content').find_all_previous(string=True)[::-1]
['HEY!', 'How are', 'you?']
相关问题