Django框架利用正则表达式提取网页邮箱地址的实现方案
本文介绍在Django框架中,通过定义正则表达式匹配规则,结合pattern库解析HTML DOM结构,自动抓取指定URL及其关联联系页面上的所有Email地址。代码包含异常处理、URL标准化及缓存机制,适用于批量获取网页联系信息场景。
本文详细介绍在Python Django框架中,利用正则表达式从网页内容中提取Email地址的具体实现方法,供开发者参考借鉴。核心逻辑如下:
import re
from django.shortcuts import render
from pattern.web import URL, DOM, abs, find_urls
def index(request):
"""
find email addresses in requested url or contact page
"""
error = ''
emails = set()
url_string = request.GET.get('url', '')
EMAIL_REGEX = re.compile(r'[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,6}', re.IGNORECASE)
# use absolute url or domain name
url = URL(url_string) if url_string.startswith('http') else URL(domain=url_string,protocol='http')
if url_string:
try:
dom = DOM(url.download(cached=True))
except Exception, e:
error = e
else:
contact_urls = { url.string }
# search links of contact page
for link in dom('a'):
if re.search(r'contact|about', link.source, re.IGNORECASE):
contact_urls.add(
abs(link.attributes.get('href',''), base=url.redirect or url.string))
for contact_url in contact_urls:
# download contact page
dom = DOM(URL(contact_url).download(cached=True))
# search emails in the body of the page
for line in dom('body')[0].content.split('\n'):
found = EMAIL_REGEX.search(line)
if found:
emails.add(found.group())
data = {
'url': url_string,
'emails': emails,
'error': error,
}
return render(request, 'index.html', data)
此外,推荐两款实用的正则表达式在线工具,便于调试与验证:
JavaScript正则表达式在线测试平台: http://tools.jb51.net/regex/javascript
正则表达式在线生成器: http://tools.jb51.net/regex/create_reg
希望上述内容能对您的Python开发工作提供有效帮助。
本站声明
本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。













