python - BeautifulSoup - 组合连续的标签

标签 python html beautifulsoup

我必须处理最困惑的 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/

相关文章:

python - 确定从 spacy 中提取的文本是否是一个完整的句子

javascript - 第二个表单出现后 -> 新表单提交时出现功能问题

html - 无法捕获的 HTML div

python - 提取文本 :after an element with Beautiful Soup

python - 使用 Python 和 BeautifulSoup 抓取时模拟单击链接

Python 的逻辑运算符 AND

python - Huey `` db_task`` 已被消费者成功注册,但未接收/执行任何任务

python - python中numpy多维数组的非相邻切片

javascript - 为什么 &lt;!--&lt;script&gt; 会在浏览器上导致 DOM 树中断?

Python 获取请求返回与查看源代码不同的 HTML