python 用正则在response.text中获取<title>标签的内容
使用正则表达式从HTTP响应文本中提取<title>
标签内容的Python实现方法:
方法一:基础正则匹配
import re
import requestsresponse = requests.get('https://example.com')
html = response.text
title = re.findall(r'<title>(.*?)</title>', html)[0] # 非贪婪匹配避免截断:ml-citation{ref="3" data="citationList"}
方法二:处理编码与异常
import re
import requeststry:response = requests.get('https://example.com')response.encoding = response.apparent_encoding # 自动检测编码:ml-citation{ref="7" data="citationList"}title_match = re.search(r'<title>(.*?)</title>', response.text)if title_match:print(title_match.group(1)) # 使用group提取捕获组内容:ml-citation{ref="5" data="citationList"}
except Exception as e:print(f"Error: {e}")
注意事项
- 编码处理:建议设置
response.encoding
避免乱码,优先使用apparent_encoding
自动检测 - 正则优化:非贪婪模式
.*?
可防止匹配到后续闭合标签 - 异常捕获:网络请求需包裹在try-except中处理超时等问题
- 替代方案:复杂HTML解析推荐使用BeautifulSoup,正则更适用于简单场景
如需处理动态加载页面,可结合Selenium获取完整DOM后再提取。