[英]lxml/beautifulsoup: Extracting text between two different tags
[英]Extracting everything between two lxml tags Python
考慮以下 html 片段
<html>. . . <div> <p> Hello </p> <div> <b> Text1 </b> <p> This is a huge paragraph text </p>. . . </div> </div>. . . <div> <i> Text2 </i> </div>
假設我需要提取從Text1
到Text2
的所有內容,包括標簽。 使用一些方法,我已經能夠提取這兩個的標簽,即它們的唯一 ID。
基本上我有 2 個 Element.etree 元素,對應於我需要的兩個標簽。
如何提取兩個標簽之間的所有內容?
(我能想到的一個可能的解決方案是找到兩個標簽的共同祖先,然后執行iterwalk()
並在 Element1 處開始提取,並在 2 處停止。但是,我不完全確定這將如何)任何解決方案都會受到贊賞。
請注意,我已經找到了我需要的兩個標簽,並且我不是在尋找找到這些標簽的解決方案(例如使用 xpath)
編輯:我想要的 output 是
<b> Text1 </b> <p> This is a huge paragraph text </p>. . . </div> </div>. . . <div> <i> Text2 </i>
請注意,我不介意最初的 2 個<div>
標簽,但不想要Hello
。 結尾的結束標簽也是如此。 我最感興趣的是中間的內容。
編輯 2:我已經使用復雜的 xpath 條件提取了 Etree 元素,這對於 bs4 等其他替代方案是不可行的,因此任何使用 lxml 元素的解決方案都將不勝感激:)
經過審查和提問:
from essentials.tokening import CreateToken # This was imported just to generate a random string - pip install mknxgn_essentials
import bs4
HTML = """<html>
<div>
<div>
<div id="start">
Hello, My name is mark
</div>
</div>
</div>
<div>
This is in the middle
</div>
<div>
<div id="end">
This is the end
</div>
</div>
<div>
Do not include this.
</div>
</html>"""
RandomString = CreateToken(30, HTML) #Generate a random string that could never occur on it's own in the file, if it did occur, use something else
soup = bs4.BeautifulSoup(HTML, features="lxml") # Convert the text into soup
start_div = soup.find("div", attrs={"id": "start"}) #assuming you can find this element
start_div.insert_before(RandomString) # insert the random string before this element
end_div = soup.find("div", attrs={"id": "end"}) #again, i was assuming you can also find this element
end_div.insert_after(RandomString) # insert the random string after this element
print(str(soup).split(RandomString)[1]) # Get between both random strings
此返回的 output :
>>> <div id="start">
>>> Hello, My name is mark
>>> </div>
>>> </div>
>>> </div>
>>> <div>
>>> This is in the middle
>>> </div>
>>> <div>
>>> <div id="end">
>>> This is the end
>>> </div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.