python 用正则在response.text中获取<title>标签的内容

使用正则表达式从HTTP响应文本中提取<title>标签内容的Python实现方法:

方法一:基础正则匹配

import re
import requests

response = 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 requests

try:
    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}")

注意事项

  1. 编码处理‌:建议设置response.encoding避免乱码,优先使用apparent_encoding自动检测
  2. 正则优化‌:非贪婪模式.*?可防止匹配到后续闭合标签
  3. 异常捕获‌:网络请求需包裹在try-except中处理超时等问题
  4. 替代方案‌:复杂HTML解析推荐使用BeautifulSoup,正则更适用于简单场景

如需处理动态加载页面,可结合Selenium获取完整DOM后再提取。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

StevenChen85

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值