[英]How to render inline element using beautiful soup 4
I am converting tag to confluence macro using bs4我正在使用 bs4 将标签转换为汇合宏
input:输入:
<p>
<img src="path/to/file.jpg" />
</p>
expected output:预期输出:
<p>
<ac:image ac:align="center" ac:layout="center">
<ri:attachment ri:filename="file.jpg" ri:version-at-save="1" />
</ac:image>
</p>
Here's the function that's being used to achieve it这是用于实现它的功能
def transform_img_to_confluence(soup):
def get_image_tag(image_name):
return BeautifulSoup(textwrap.dedent('''
<ac:image ac:align="center" ac:layout="center">
<ri:attachment ri:filename="{}" ri:version-at-save="1" />
</ac:image>
''').format(image_name), "html.parser")
for img in soup.find_all('img'):
path = img['src']
image_name = os.path.basename(path)
image_tag = get_image_tag(image_name)
img.replace_with(image_tag)
soup = BeautifulSoup(html_string, "html.parser")
transform_img_to_confluence(soup)
print(soup.prettify())
When I inspect soup after calling this function, I'm expecting tags to be replaced to the following ( ri:attachment
element as inline )当我在调用此函数后检查汤时,我希望将标签替换为以下内容(
ri:attachment
元素作为内联)
<ac:image ac:align="center" ac:layout="center">
<ri:attachment ri:filename="file.jpg" ri:version-at-save="1" />
</ac:image>
but unfortunately I'm getting this instead.但不幸的是,我得到了这个。 (
ri:attachment
with open and close tags ) (
ri:attachment
带有打开和关闭标签的ri:attachment
)
<ac:image ac:align="center" ac:layout="center">
<ri:attachment ri:filename="file.jpg" ri:version-at-save="1">
</ri:attachment>
</ac:image>
How to make sure I'm getting the desired inline element ?如何确保获得所需的内联元素?
the problem comes from the parser.问题来自解析器。 in your case
lxml-xml
should do.在你的情况下
lxml-xml
应该做。 here are some example outputs from available parsers以下是可用解析器的一些示例输出
from bs4 import BeautifulSoup
a="""<a><b /></a>"""
print(BeautifulSoup(a, 'lxml'))
>>> <html><body><a><b></b></a></body></html>
print(BeautifulSoup(a, 'lxml-xml'))
>>> <?xml version="1.0" encoding="utf-8"?>
>>> <a><b/></a>
print(BeautifulSoup(a, 'html.parser'))
>>> <a><b></b></a>
print(BeautifulSoup(a, 'html5lib'))
>>> <html><head></head><body><a><b></b></a></body></html>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.