如何删除BeautifulSoup中不同头尾的标签?

2024-10-01 00:29:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在用BeautifulSoup抓取一个网页。当我清理html时,我遇到一个具有不同头尾的标记:

<!-- BEGIN mobile-middle-rectangle --> <div class="mobile-bottom-rectangle hidden-sm hidden-md hidden-lg"> <div class="textrule"> <span>advertisement</span> </div> <!-- /1002721/ScienceDaily_Mobile_Bottom_Rectangle --> <div id="adslot-mobile-bottom-rectangle"> <script type="text/javascript"> googletag.cmd.push(function() { deployads.push(function() { deployads.gpt.display("adslot-mobile-bottom-rectangle") }); }); </script> </div> <hr class="hrrule"> </div> <!-- END mobile-middle-rectangle -->

我怎样才能删除它


Tags: div网页middlescriptfunctionmobilepushhidden
1条回答
网友
1楼 · 发布于 2024-10-01 00:29:14

通常,您应该使用正则表达式。 如果要删除以这些类型的标记(<! BEGIN/END whatever >)开头和结尾的所有标记,请使用以下命令:

re.sub("<!  BEGIN.*>\n(<?.+>?\s+)+<!  END.* >", "", html)

如果要在这些标记之间保存内容,请使用以下命令:

cleaned = re.sub(r"<!  BEGIN.*>\n((<?.+>?\s+)+)<!  END.* >", r"\1", html)

相关问题 更多 >