2010-04-28 78 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