我想用正则表达式从HTML页面中提取标题。目前我有这个:

title = re.search('<title>.*</title>', html, re.IGNORECASE).group()
if title:
    title = title.replace('<title>', '').replace('</title>', '') 

是否有正则表达式来提取<title>的内容,这样我就不必删除标签了?


当前回答

在regexp中使用(),在python中使用group(1)来检索捕获的字符串(re.search如果没有找到结果将返回None,所以不要直接使用group()):

title_search = re.search('<title>(.*)</title>', html, re.IGNORECASE)

if title_search:
    title = title_search.group(1)

其他回答

尝试使用捕获组:

title = re.search('<title>(.*)</title>', html, re.IGNORECASE).group(1)

所提供的代码段不能处理异常 我可以建议

getattr(re.search(r"<title>(.*)</title>", s, re.IGNORECASE), 'groups', lambda:[u""])()[0]

默认情况下,如果没有找到模式或第一个匹配,则返回空字符串。

Krzysztof krasosk目前投票最多的答案是<title>a</title><title>b</title>。此外,它忽略了跨越行边界的标题标签,例如,由于行长原因。最后,它失败于<title >a</title>(这是有效的XML/HTML标记中的空白)。

因此,我提出以下改进建议:

import re

def search_title(html):
    m = re.search(r"<title\s*>(.*?)</title\s*>", html, re.IGNORECASE | re.DOTALL)
    return m.group(1) if m else None

测试用例:

print(search_title("<title   >with spaces in tags</title >"))
print(search_title("<title\n>with newline in tags</title\n>"))
print(search_title("<title>first of two titles</title><title>second title</title>"))
print(search_title("<title>with newline\n in title</title\n>"))

输出:

with spaces in tags
with newline in tags
first of two titles
with newline
  in title

最后,我和其他人一起推荐一个HTML解析器——不仅要处理HTML标记的非标准使用。

没有人建议使用前视和后视,有什么特别的原因吗?我在这里试图做完全相同的事情和(?<=<title>).+(?=<\/title>)工作得很好。它只会匹配括号之间的内容所以你不需要做整个组的事情。

在regexp中使用(),在python中使用group(1)来检索捕获的字符串(re.search如果没有找到结果将返回None,所以不要直接使用group()):

title_search = re.search('<title>(.*)</title>', html, re.IGNORECASE)

if title_search:
    title = title_search.group(1)