python - BeautifulSoup 结契约(Contract)名标签

标签 python xml beautifulsoup

我有多个标题标签,我想将它们合并为一个标题标签。下面是我所拥有的:(我想组合标题标签,以便当我打印汤时,标签在一起并且我不希望它们成为字符串)

<title>
  <b> Title Name 1 </b>
</title> 
<title>
  Title Name 2
</title>

这是我想要的输出:

<title>
  <b> Title Name 1 </b> Title Name 2
</title> 

这是我到目前为止尝试做的事情: 我创建了一个新标签,然后尝试将所有标题标签添加到其中,以便稍后我可以打开标题标签并留下一个标签:

<title>
  <b> Title Name 1 </b>
</title> 
<title>
  Title Name 2
</title>
<final-title>
</final-title>


for item in soup.findAll(['title', 'final-title']):
    if item.name == 'final-title':
        text = item
    if item.name == 'title':
        text.insert(len(text.contents),item)

但是,此方法无法获取适当的标题名称,因为我有很多这样的标题标签。我也尝试过使用与此类似的东西( Wrap multiple tags with BeautifulSoup )

最佳答案

使用.insert()您需要将字符串转换为 list()但我认为创建<title>的列表innerHTML更容易与 .encode_contents() ,然后将其合并。

from bs4 import BeautifulSoup

html_raw = '''<title>
  <b> Title Name 1 </b>
</title> 
<title>Title Name 2</title>
<final-title>
</final-title>
'''
title = []
soup = BeautifulSoup(html_raw, 'html.parser')

for item in soup.findAll(['title', 'final-title']):
    if item.name == 'title':
        title.append(item.encode_contents().strip())

combinedTitle = '<title>%s</title>' % ' '.join(title)

print combinedTitle
# output
# <title><b> Title Name 1 </b> Title Name 2</title>

关于python - BeautifulSoup 结契约(Contract)名标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53230710/

相关文章:

python - 在 MoviePy 中混合音频文件

c# - 使用 LINQ,如何将分层 XML 加载到 POCO 中?

java - 如何在位图上居中和缩放叠加的可绘制图标

Python - BeautifulSoup,在标签中获取标签

python - 使用 BeautifulSoup 获取具有此属性的最近的前一个元素

python - 如何从这种情况下用 python 删除 <table> 结构?

python - 使用 pip 安装模块,未找到

python - AzureML : Dataset Profile fails when parquet file is empty

python - 从 pandas 表中选取/过滤元素,其中数据位于列标题值之间

android - 制作圆形 FrameLayout