<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/