html - 如何删除 beautifulsoup 中特定模式内的任何 html 标签

标签 html regex python-2.7 beautifulsoup

<p>
 A 
 <span>die</span> 
  is thrown \(x = {-b \pm 
  <span>\sqrt</span>
  {b^2-4ac} \over 2a}\) twice. What is the probability of getting a sum 7 from
both the throws?
</p>

在上面的 html 中,我只需要删除“\(tags\)”中的标签,即 \(x = {-b \pm <span>\sqrt</span> {b^2-4ac} \over 2a}\\) 。 我刚刚开始使用 beautifulsoup 有什么方法可以通过 beautifulsoup 实现这一点吗?

最佳答案

我想出了我的问题的解决方案。希望它对其他人有帮助。请随时给我改进代码的建议。

from bs4 import BeautifulSoup
import re
html = """<p>
     A 
     <span>die</span> 
      is thrown \(x = {-b \pm 
      <span>\sqrt</span>
      {b^2-4ac} \over 2a}\) twice. What is the probability of getting a sum 7 from
    both the throws?
    </p> <p> Test </p>"""

soup = BeautifulSoup(html, 'html.parser')
mathml_start_regex = re.compile(r'\\\(')
mathml_end_regex = re.compile(r'\\\)')

for p_tags in soup.find_all('p'):
    match = 0 #Flag set to 1 if '\(' is found and again set back to 0 if '\)' is found.
    for p_child in p_tags.children:
        try: #Captures Tags that contains \(
            if re.findall(mathml_start_regex, p_child.text):
                match += 1
        except: #Captures NavigableString that contains \(
            if re.findall(mathml_start_regex, p_child):
                match += 1
        try: #Replaces Tag with Tag's text
            if match == 1:
                p_child.replace_with(p_child.text)
        except: #No point in replacing NavigableString since they are just strings without Tags
            pass
        try: #Captures Tags that contains \)
            if re.findall(mathml_end_regex, p_child.text):
                match = 0
        except: #Captures NavigableString that contains \)
            if re.findall(mathml_end_regex, p_child):
                match = 0

输出:

<p>
     A 
     <span>die</span> 
      is thrown \(x = {-b \pm 
      \sqrt
      {b^2-4ac} \over 2a}\) twice. What is the probability of getting a sum 7 from
    both the throws?
    </p>
<p> Test
</p>

在上面的代码中,我搜索了所有“p”标签,它返回bs4.element.ResultSet。在第一个 for 循环中,我迭代结果集以获取单独的“p”标签,在第二个 for 循环中,我使用 .children 生成器迭代“p”标签子项(包含可导航字符串和标签)。每个“p”标签的子标签都会搜索“\(”,如果找到,则匹配设置为 1,如果迭代到匹配的子标签时为 1,则使用replace_with 删除特定子标签中的标签em> 最后,当找到 '\)' 时,匹配项设置为零。

关于html - 如何删除 beautifulsoup 中特定模式内的任何 html 标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42040026/

相关文章:

html - 绝对定位内容重叠页脚

javascript - 如何使用 html 模式验证澳大利亚电话号码

regex - 如何从字符串中删除第一个和最后一个破折号?

Python 代码在 Jinja 模板中的工作方式不相似

python - 将时间单位作为变量传递给时间增量函数中的关键字参数。

python - 如何使用另一个列表中的匹配值索引来复制列表值?

javascript - JS 无法在 Firefox 上运行

html - 没有固定高度的垂直 div 扩展

regex - 使用 str replace 删除 json 文档中的部分字符串用于许多记录

regex - 正则表达式匹配逗号不在 rust 引号内