在Python BeautifulSoup中如何移动标签
我有一个从HTML转换过来的部分XML文档,里面是一些内容。在对这些内容进行了一些替换和编辑后,文档的主体基本上是这样的 -
<Text...></Text> # This replaces <a href..> tags but automatically creates the </Text>
<p class=norm ...</p>
<p class=norm ...</p>
<Text...></Text>
<p class=norm ...</p> and so forth.
我需要把 <p>
标签“移动”到 <Text>
标签下面,或者知道怎么去掉 </Text>
标签。我想要的结果是 -
<Text...>
<p class=norm ...</p>
<p class=norm ...</p>
</Text>
<Text...>
<p class=norm ...</p>
</Text>
我试过使用 item.insert 和 item.append,但我觉得应该有更优雅的解决办法。
for item in soup.findAll(['p','span']):
if item.name == 'span' and item.has_key('class') and item['class'] == 'section':
xBCV = short_2_long(item._getAttrMap().get('value',''))
if currentnode:
pass
currentnode = Tag(soup,'Text', attrs=[('TypeOf', 'Section'),... ])
item.replaceWith(currentnode) # works but creates end tag
elif item.name == 'p' and item.has_key('class') and item['class'] == 'norm':
childcdatanode = None
for ahref in item.findAll('a'):
if childcdatanode:
pass
newlink = filter_hrefs(str(ahref))
childcdatanode = Tag(soup, newlink)
ahref.replaceWith(childcdatanode)
谢谢
1 个回答
4
你可以使用insert来移动标签。文档中提到:“一个元素在一个解析树中只能出现一次。如果你给insert一个已经连接到soup对象的元素,它会先被断开(用extract方法),然后再连接到其他地方。”
如果你的HTML看起来像这样:
<text></text>
<p class="norm">1</p>
<p class="norm">2</p>
<text></text>
<p class="norm">3</p>
... 这样:
for item in soup.findAll(['text', 'p']):
if item.name == 'text':
text = item
if item.name == 'p':
text.insert(len(text.contents), item)
... 将会产生以下结果:
<text><p class="norm">1</p><p class="norm">2</p></text>
<text><p class="norm">3</p></text>