无法在BeautifulSoup中添加文本和链接到新标签

时间:2018-11-22 18:21:20

标签: python beautifulsoup

我抓取了以下HTML以获得链接信息,创建了一个新标签,将该链接添加到新标签中,然后尝试将该标签附加到另一个文档中,但是丢失了所有HTML格式:

data = """
<div class="Answer">
1. BOUNDARIES - EPB &amp; APL&nbsp;<i>(inferior)</i>, EPL&nbsp;<i>(superior).&nbsp;</i><div>2. FLOOR (proximal to distal) - radial styloid =&gt; scaphoid =&gt; trapezium =&gt; 1st MC base.&nbsp;<br /><div>3. CONTENTS - cutaneous branches of radial nerve&nbsp;<i>(on the roof),</i>&nbsp;cephalic vein&nbsp;<i>(begins here),</i>&nbsp;&nbsp;radial artery&nbsp;<i>(on the floor).</i></div></div><div><br /></div><div><img src="paste-27a44c801f0776d91f5f6a16a963bff67f0e8ef3.jpg" /><br /></div><div><b>Image:&nbsp;</b>Case courtesy of Dr Sachintha Hapugoda, &lt;a href="https://radiopaedia.org/"&gt;Radiopaedia.org&lt;/a&gt;. From the case &lt;a href="https://radiopaedia.org/cases/52525"&gt;rID: 52525&lt;/a&gt; [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, &lt;a href="https://radiopaedia.org/"&gt;Radiopaedia.org&lt;/a&gt;. From the case &lt;a href="https://radiopaedia.org/cases/52525"&gt;rID: 52525&lt;/a&gt; [Accessed 15 Nov. 2018].</p>

所有HTML格式均丢失。我该怎么办?

1 个答案:

答案 0 :(得分:2)

由于.c的类型为image_link或字符串,它将把NavigableString之类的字符转换为<,因此您需要通过创建新的{ {1}}

&lt;

或取消转义结果

Tag