2

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)

ありがとう

4

1 に答える 1

3

insertを使用してタグを移動できます。ドキュメントには次のように書かれています。「要素は 1 つの解析ツリー内の 1 つの場所でのみ発生します。すでにスープ オブジェクトに接続されている要素を挿入すると、他の場所に接続される前に (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>
于 2010-04-28T22:52:22.867 に答える