[英]BeautifulSoup : create and insert self closing tag between a tag
我正在解析 html 文件並用新標簽替換特定鏈接。
Python 代碼:
from bs4 import BeautifulSoup
sample='''<a href="{Image src='https://google.com' link='https://google.com'}" >{Image src='https://google.com' link='google.com'}</a>'''
soup=BeautifulSoup(sample)
for a in soup.findAll('a'):
x=BeautifulSoup('<ac:image><ri:attachment ri:filename="somefile"/> </ac:image>')
a=a.replace_with(x)
print(soup)
實際 Output:
<ac:image><ri:attachment ri:filename="somefile"></ri:attachment> </ac:image>
所需的 Output:
<ac:image><ri:attachment ri:filename="somefile" /></ac:image>
自關閉標簽會自動轉換。 目的地嚴格需要自閉標簽。
任何幫助,將不勝感激!
要獲得正確的自閉合標簽,請在創建將替換舊標簽的新湯時使用解析器xml
。
此外,為了保留ac
和ri
命名空間, xml
解析器需要定義xmlns:ac
和xmlns:ri
參數。 我們在處理后刪除的虛擬標簽中定義這些參數。
例如:
from bs4 import BeautifulSoup
import xml
txt = '''
<div class="my-class">
<a src="some address">
<img src="attlasian_logo.gif" />
</a>
</div>
<div class="my-class">
<a src="some address2">
<img src="other_logo.gif" />
</a>
</div>
'''
template = '''
<div class="_remove_me" xmlns:ac="http://namespace1/" xmlns:ri="http://namespace2/">
<ac:image>
<ri:attachment ri:filename="{img_src}" />
</ac:image>
</div>
'''
soup = BeautifulSoup(txt, 'html.parser')
for a in soup.select('a'):
a=a.replace_with(BeautifulSoup(template.format(img_src=a.img['src']), 'xml')) # <-- select `xml` parser, the template needs to have xmlns:* parameters to preserve namespaces
for div in soup.select('div._remove_me'):
dump=div.unwrap()
print(soup.prettify())
印刷:
<div class="my-class">
<ac:image>
<ri:attachment ri:filename="attlasian_logo.gif"/>
</ac:image>
</div>
<div class="my-class">
<ac:image>
<ri:attachment ri:filename="other_logo.gif"/>
</ac:image>
</div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.