在Python BeautifulSoup中如何移动标签

时间:2010-04-28 19:04:53

标签: python xml regex beautifulsoup children

我有来自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 个答案:

答案 0 :(得分:2)

您可以使用insert移动代码。文档说:“元素只能出现在一个解析树中的一个位置。如果你给插入一个已经连接到汤对象的元素,它会在连接到其他地方之前断开连接(使用提取)。”

如果你的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>