[英]How to extract html between two different tags in python?
我有以下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或其他一些庫?)
使用BeautifulSoup,使用.next_siblings
可迭代以獲取標簽后面的文本:
>>> 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
元素之后的所有文本元素, soup.h2
它們連接到一個字符串中。
這是來自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 ')]
讓我分享一個更強大的解決方案:
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>
。 它很容易修改以將文本從標簽提取到另一個標簽。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.