【问题标题】:In Python BeautifulSoup How to move tags在 Python BeautifulSoup 中如何移动标签
【发布时间】:2011-02-13 12:20:02
【问题描述】:

我有一个来自 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.  

我需要将&lt;p&gt; 标签“移动”为&lt;Text&gt; 的子标签,或者知道如何抑制&lt;/Text&gt;。我要-

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

谢谢

【问题讨论】:

  • 让您知道 JJ,html/xml 标签不会出现在您的问题中,除非您使用 ``s 转义它们(如果它是句子中的一小部分),或者如果它们是代码块合适的。这次我修好了,但我认为你应该知道未来。
  • 谢谢。我想知道这是如何工作的。感谢您的监督和帮助。

标签: python xml regex beautifulsoup children


【解决方案1】:

您可以使用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>

【讨论】:

  • 酷。这很有帮助。我会试一试,看看它是如何工作的。字里行间我一定读得不够深入。
猜你喜欢
  • 2012-01-12
  • 2020-12-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多