2010-04-28 75 views
1

我有一个来自HTML的汤的部分转换XML文档。一些置换和编辑的汤后,身体基本上是 -在Python BeautifulSoup如何移动标签

<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) 

感谢

+0

只要你知道JJ, html/xml标签不会出现在你的问题中,除非你用“s”来转义它们,如果它是句子中的一小块,或者在适当的时候使它们成为代码块。这次我修好了,但我认为你应该知道未来。 – 2010-04-28 20:31:33

+0

谢谢。我想知道这是如何工作的。我感谢您的监督和协助。 – user3591360 2010-04-30 13:00:25

回答

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> 
+0

很酷。这很有帮助。我会给它一个旋转,看看它是如何工作的。我不能在两条线之间深入阅读。 – user3591360 2010-04-30 12:59:15