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

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

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


当前回答

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

其他回答

Try:

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

我可以向您推荐美丽汤吗?Soup是一个解析所有html文档的很好的库。

soup = BeatifulSoup(html_doc)
titleName = soup.title.name

请注意,从Python 3.8开始,并引入了赋值表达式(PEP 572)(:=操作符),可以通过直接在if条件中捕获匹配结果作为变量并在条件体中重用它来改进Krzysztof krasosco的解决方案:

# pattern = '<title>(.*)</title>'
# text = '<title>hello</title>'
if match := re.search(pattern, text, re.IGNORECASE):
  title = match.group(1)
# hello
re.search('<title>(.*)</title>', s, re.IGNORECASE).group(1)

在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)