使用python在html标记之间查找和替换

2024-07-03 07:33:22 发布

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

我正在尝试向HTML文件集添加一行。在

我想把它放在</h1><p>标记之间,所以我试图找到能够捕捉这些标记之间的所有内容(可能有新行、空格或其他内容)的regex,然后用我以前准备好的html行替换它

到目前为止,我有这个:

for i in filesToBeChanged:
    lines = codecs.open(i,'r','utf-8').readlines()
    for line in lines:
        if line.find('</h1>') != -1: #here I probably need some .replace() :)
            print line

Tags: 文件in标记内容forhtmllineopen
3条回答

您可以将following regexre.sub一起使用:

(?s)<\/h1>(.*?)<p>

(?s)启用单线模式,以便.与换行符匹配。在

样本代码:

^{pr2}$

最好使用beautifulSoup或{a2}进行html处理。在

像这样:

from bs4 import BeautifulSoup

html_doc = """
<h1>First header</h1>
<p>first paragraph</p>
<h1>Second header</h1>
<p>second paragraph</p>
<h3>Third header</h3>
"""

soup = BeautifulSoup(html_doc)
for h1 in soup.findAll('h1'):
    if h1.find_next_sibling('p'):
        h1.insert_after('\nSome text')
print soup

输出:

^{pr2}$

如果您可以使用lookaheads和lookback,那么应该可以:

(?<=\<\/h1\>)[\S\s]*(?=\<p\>)

相关问题 更多 >