我抓取了以下HTML以获得链接信息,创建了一个新标签,将该链接添加到新标签中,然后尝试将该标签附加到另一个文档中,但是丢失了所有HTML格式:
data = """
<div class="Answer">
1. BOUNDARIES - EPB & APL <i>(inferior)</i>, EPL <i>(superior). </i><div>2. FLOOR (proximal to distal) - radial styloid => scaphoid => trapezium => 1st MC base. <br /><div>3. CONTENTS - cutaneous branches of radial nerve <i>(on the roof),</i> cephalic vein <i>(begins here),</i> radial artery <i>(on the floor).</i></div></div><div><br /></div><div><img src="paste-27a44c801f0776d91f5f6a16a963bff67f0e8ef3.jpg" /><br /></div><div><b>Image: </b>Case courtesy of Dr Sachintha Hapugoda, <a href="https://radiopaedia.org/">Radiopaedia.org</a>. From the case <a href="https://radiopaedia.org/cases/52525">rID: 52525</a> [Accessed 15 Nov. 2018].</div>
</div>
"""
soup = BeautifulSoup(data, "html.parser")
image_link = soup.find('div').find('b').next.next
print(image_link)
我抓取了以上数据以获取以下参考链接(这是我要求的格式):
Case courtesy of Dr Sachintha Hapugoda, <a href="https://radiopaedia.org/">Radiopaedia.org</a>. From the case <a href="https://radiopaedia.org/cases/52525">rID: 52525</a> [Accessed 15 Nov. 2018].
但是将上述参考链接添加到新标签会丢失所有HTML格式:
p_tag = soup.new_tag('p')
p_tag.append(soup.new_tag('br'))
p_tag.append(soup.new_tag('b'))
p_tag.b.append("Image: ")
p_tag.append(NavigableString(image_link))
print(p_tag)
返回:
<p><br/><b>Image: </b>Case courtesy of Dr Sachintha Hapugoda, <a href="https://radiopaedia.org/">Radiopaedia.org</a>. From the case <a href="https://radiopaedia.org/cases/52525">rID: 52525</a> [Accessed 15 Nov. 2018].</p>
所有HTML格式均丢失。我该怎么办?
答案 0 :(得分:2)
由于.c
的类型为image_link
或字符串,它将把NavigableString
之类的字符转换为<
,因此您需要通过创建新的{ {1}}
<
或取消转义结果
Tag