我需要找到所有PHP标签,但是当遇到调用带有“ - >”的方法的类时,我遇到了麻烦 . 它选择“>”作为结束标记 .

PHP标签: <html><body> Blah Blah Blah... <h2>Section Heading <?php $playFrom->time("09:58"); ?></h2>Blah blah blah </body></html>

我的代码:

taglist = soup.findAll("?php")
for tag in taglist:
    tag.replaceWith("")

替换为 <h2>Section Heading time("09:58"); ?&gt;

BeautifulSoup可以这样做吗?如果是这样,那么正确的方法是什么?

编辑(1):正如瑞恩指出:

“PHP不是HTML,所以你无法用HTML解析器真正解析它 . ”

我发现汤解析器会自动删除PHP并留下所有在 <h2> 标签文本中的碎片 . 所以 my solution 是用 findall('h2') ... text.replace('badstuff', 'good stuff') ... My new question is 来清理那个文本,因为lxml是默认的解析器(根据这个链接:Set lxml as default BeautifulSoup parser),我不应该仍然能找到一种方法来干净地删除PHP使用BS4?

注意(我的解决方案):通过消除上面的 findAll("?php")... 代码,我只需让BS4汤解析HTML,就可以得到 <h2> 标签的以下结果 .

<h2>Section Heading <?php $playFrom->time("09:58"); ?></h2>

成为这个:

<h2>Section Heading time("09:58"); ?&gt;</h2>

以上结果来自:

soup = BeautifulSoup(html.read(),'lxml')
print(soup.body.h2)
html.close()

以下代码版本清除了这个:

soup = BeautifulSoup(html.read(),'lxml') 

h2list = soup.findAll("h2")
for tag in h2list:
    text = text.replace('time("', '(')
    text = text.replace('\"); ?>', ')')
    tag.string = text

print(soup.body.h2)
html.close()

制作这个:

<h2>Section Heading (09:58)</h2>