【问题标题】:wrapping subsections of text with tags in BeautifulSoup在 BeautifulSoup 中用标签包装文本的小节
【发布时间】:2023-03-08 03:25:01
【问题描述】:

我想要与 this jQuery question 等效的 BeautifulSoup。

我想在 BeautifulSoup 文本中找到一个特定的正则表达式匹配,然后用包装的版本替换该段文本。我可以用纯文本换行来做到这一点:

# replace all words ending in "ug" wrapped in quotes,
# with "ug" replaced with "ook"

>>> soup = BeautifulSoup("Snug as a bug in a rug")
>>> soup
<html><body><p>Snug as a bug in a rug</p></body></html>
>>> for text in soup.findAll(text=True):
...   if re.search(r'ug\b',text):
...     text.replaceWith(re.sub(r'(\w*)ug\b',r'"\1ook"',text))
...
u'Snug as a bug in a rug'
>>> soup
<html><body><p>"Snook" as a "book" in a "rook"</p></body></html>

但是如果我想要粗体而不是引号怎么办?例如期望的结果 =

<html><body><p><b>Snook</b> as a <b>book</b> in a <b>rook</b></p></body></html>

【问题讨论】:

    标签: python html regex beautifulsoup


    【解决方案1】:
    for text in soup.findAll(text=True):
       if re.search(r'ug\b',text):
         text.replaceWith(BeautifulSoup(re.sub(r'(\w*)ug\b',r'<b>\1ook</b>',text),'html.parser'))
    
    soup
    Out[117]: <html><body><p><b>Snook</b> as a <b>book</b> in a <b>rook</b></p></body></html>
    

    这里的想法是我们用一个完整的解析树替换一个标签。最简单的方法是在我们的正则表达式字符串上调用BeautifulSoup

    内部BeautifulSoup 调用的有点神奇的'html.parser' 参数是为了防止它添加&lt;html&gt;&lt;body&gt;&lt;p&gt; 标签,就像bs4(嗯,真的是lxml)通常做的那样。 More reading on that.

    【讨论】:

      【解决方案2】:

      所以这是一种方法。您可以使用正则表达式创建新的 HTML,其中包含粗体字的单词,将其放入 BeautifulSoup 构造函数,然后将整个父 p 替换为新的 p 标签。

      import bs4
      import re
      
      soup = bs4.BeautifulSoup("Snug as a bug in a rug")
      print soup
      
      for text in soup.findAll(text=True):
          if re.search(r'ug\b',text):
              new_html = "<p>"+re.sub(r'(\w*)ug\b', r'<b>\1ook</b>', text)+"</p>"
              new_soup = bs4.BeautifulSoup(new_html)
              text.parent.replace_with(new_soup.p)
      
      print soup
      

      另一种选择是使用 soup.new_tag 方法,但这可能需要嵌套的 for 循环,这不会那么优雅。我看看我能不能把它写出来,稍后再贴在这里。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-05-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-07-26
        • 1970-01-01
        • 2016-10-17
        相关资源
        最近更新 更多