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编译成.so文件进行加密后调用的实现

pyc的破解相对容易,使用cython将python文件编译成.so文件,能在一定程度上增强python源码的私密性。 编译成.so文件 环境准备:cython 测试脚本准备:test....

Python pandas库中的isnull()详解

问题描述 python的pandas库中有一个十分便利的isnull()函数,它可以用来判断缺失值,我们通过几个例子学习它的使用方法。 首先我们创建一个dataframe,其中有一些数据...

python实现在windows服务中新建进程的方法

本文实例讲述了python实现在windows服务中新建进程的方法。分享给大家供大家参考。具体实现方法如下: 需要安装的软件:python和pywin32,我这里装的分别是python-...

Python numpy生成矩阵、串联矩阵代码分享

import numpy 生成numpy矩阵的几个相关函数: numpy.array() numpy.zeros() numpy.ones() numpy.eye() 串联生成num...

Python实现将不规范的英文名字首字母大写

例如 输入:['adam', 'LISA', 'barT'],输出:['Adam', 'Lisa', 'Bart']。 方法一 def wgw(x): return [x[0]...