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