gpt4 book ai didi

python - 在Python BeautifulSoup中如何移动标签

转载 作者:行者123 更新时间:2023-12-01 06:17:00 25 4
gpt4 key购买 nike

我在 soup 中有一个来自 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)

谢谢

最佳答案

您可以使用insert移动标签。文档说:“一个元素只能出现在一个解析树中的一个位置。如果你插入一个已经连接到 soup 对象的元素,它会在连接到其他地方之前断开(与 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>

关于python - 在Python BeautifulSoup中如何移动标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2732391/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com