gpt4 book ai didi

python - BeautifulSoup - 组合连续的标签

转载 作者:太空狗 更新时间:2023-10-30 02:37:30 25 4
gpt4 key购买 nike

我必须处理最困惑的 HTML,其中单个单词被分成单独的标签,如以下示例所示:

<b style="mso-bidi-font-weight:normal"><span style='font-size:14.0pt;mso-bidi-font-size:11.0pt;line-height:107%;font-family:"Times New Roman",serif;mso-fareast-font-family:"Times New Roman"'>I</span></b><b style="mso-bidi-font-weight:normal"><span style='font-family:"Times New Roman",serif;mso-fareast-font-family:"Times New Roman"'>NTRODUCTION</span></b>

这有点难读,但基本上“INTRODUCTION”这个词被分成了

<b><span>I</span></b> 

<b><span>NTRODUCTION</span></b>

span 和 b 标签具有相同的内联属性。

结合这些的好方法是什么?我想我会循环查找像这样的连续 b 标签,但我仍然坚持如何合并连续的 b 标签。

for b in soup.findAll('b'):
try:
if b.next_sibling.name=='b':
## combine them here??
except:
pass

有什么想法吗?

编辑:预期输出如下

<b style="mso-bidi-font-weight:normal"><span style='font-family:"Times New Roman",serif;mso-fareast-font-family:"Times New Roman"'>INTRODUCTION</span></b>

最佳答案

下面的解决方案结合了所有选定的 <b> 中的文本标签合二为一<b>您选择的并分解其他的。

如果您只想合并来自连续标签的文本,请遵循 Danny's方法。

代码:

from bs4 import BeautifulSoup

html = '''
<div id="wrapper">
<b style="mso-bidi-font-weight:normal">
<span style='font-size:14.0pt;mso-bidi-font-size:11.0pt;line-height:107%;font-family:"Times New Roman",serif;mso-fareast-font-family:"Times New Roman"'>I</span>
</b>
<b style="mso-bidi-font-weight:normal">
<span style='font-family:"Times New Roman",serif;mso-fareast-font-family:"Times New Roman"'>NTRODUCTION</span>
</b>
</div>
'''

soup = BeautifulSoup(html, 'lxml')
container = soup.select_one('#wrapper') # it contains b tags to combine
b_tags = container.find_all('b')

# combine all the text from b tags
text = ''.join(b.get_text(strip=True) for b in b_tags)

# here you choose a tag you want to preserve and update its text
b_main = b_tags[0] # you can target it however you want, I just take the first one from the list
b_main.span.string = text # replace the text

for tag in b_tags:
if tag is not b_main:
tag.decompose()

print(soup)

任何评论表示赞赏。

关于python - BeautifulSoup - 组合连续的标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50026264/

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