【问题标题】:BeautifulSoup - Highlight the anchor text within other textBeautifulSoup - 突出显示其他文本中的锚文本
【发布时间】:2018-11-04 08:01:29
【问题描述】:

这是我所拥有的示例:

<text>This sign is <a href="http://XXXX"> select color </a> in color <text>

这是我想提取文本的方式:

这个标志是选择颜色的颜色

我正在使用美丽的汤。这就是我正在做的事情。

text = soup.find_all('text')

for t in text:

   print t.get_text()

我明白了:这个标志是颜色中的选择颜色

是否可以突出显示/粗体/斜体锚标记中的文本? (这个标志是select color的颜色)

【问题讨论】:

  • 您是否只想将所有超链接标签 (<a>) 更改为粗体标签 (<b>)?
  • 如果是这种情况,您可以尝试使用 BeautifulSoup 抓取每一行,然后使用正则表达式 (import re) 将超链接标签替换为粗体标签。
  • 你想在终端上用“粗体”打印它吗?
  • @Bijoy 是的,我需要用粗体打印出来
  • @Chris 和 Kyle,我需要它在打印时以粗体显示。

标签: python parsing beautifulsoup


【解决方案1】:

您可以使用wrapunwrap

演示:

from bs4 import BeautifulSoup
s = """<text>This sign is <a href="http://XXXX"> select color </a> in color <text>"""
soup = BeautifulSoup(s, "html.parser")
for t in soup.find_all('text'):
    if t.a:
        t.a.wrap(soup.new_tag("b")).find("a").unwrap()
        print(t)

输出:

<text>This sign is <b> select color </b> in color <text></text></text>

【讨论】:

猜你喜欢
  • 2013-03-01
  • 1970-01-01
  • 2016-11-25
  • 1970-01-01
  • 2011-08-31
  • 2019-08-13
  • 1970-01-01
  • 2015-05-29
  • 2016-06-09
相关资源
最近更新 更多