python中django框架通过正则搜索页面上email地址的方法

yipeiwu_com5年前Python基础

本文实例讲述了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)

PS:这里再为大家提供2款非常方便的正则表达式工具供大家参考使用:

JavaScript正则表达式在线测试工具:
http://tools.jb51.net/regex/javascript

正则表达式在线生成工具:
http://tools.jb51.net/regex/create_reg

希望本文所述对大家的Python程序设计有所帮助。

相关文章

Python语言描述连续子数组的最大和

题目描述 HZ偶尔会拿些专业问题来忽悠那些非计算机专业的同学。今天测试组开完会后,他又发话了:在古老的一维模式识别中,常常需要计算连续子向量的最大和,当向量全为正数的时候,问题很好解决。...

详解Python的Django框架中Manager方法的使用

在语句Book.objects.all()中,objects是一个特殊的属性,需要通过它查询数据库。 在第5章,我们只是简要地说这是模块的manager 。现在是时候深入了解manage...

python 经典数字滤波实例

python 经典数字滤波实例

数字滤波分为 IIR 滤波,和FIR 滤波。 FIR 滤波: import scipy.signal as signal import numpy as np import pyla...

Python Pywavelet 小波阈值实例

小波应用比较广泛,近期想使用其去噪。由于网上都是matlib实现,故记下一下Python的使用 Pywavelet  Denoising 小波去噪  # -*-...

详解Python3中ceil()函数用法

详解Python3中ceil()函数用法

描述 ceil(x) 函数返回一个大于或等于 x 的的最小整数。 语法 以下是 ceil() 方法的语法: import math math.ceil( x ) 注意:cei...