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

yipeiwu_com6年前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中将函数赋值给变量时需要注意的一些问题

前言 本文主要给大家介绍的是关于python将函数赋值给变量时需要注意的一些问题,分享出来供大家参考学习,下面话不多说了,来一起看看详细的介绍: 见过两种函数赋值给变量的形式,一种是...

Python中的四种交换数值的方法解析

Python中的四种交换数值的方法解析

这篇文章主要介绍了Python中的四种交换数值的方法解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 交换两个变量的值方法,这个面试...

详解Python中的内建函数,可迭代对象,迭代器

详解Python中的内建函数,可迭代对象,迭代器

Python中的内建函数和可迭代对象,迭代器 求值标识 id() #标识id 返回对象的唯一标识,CPython返回内存地址 hash() #哈希, 返回对象的哈希值 le...

解决Python requests 报错方法集锦

python版本和ssl版本都会导致 requests在请求https网站时候会出一些错误,最好使用新版本。 1 Python2.6x use requests 一台老Centos机器上...

如何通过50行Python代码获取公众号全部文章

如何通过50行Python代码获取公众号全部文章

前言 我们平时阅读公众号的文章会遇到一个问题——阅读历史文章体验不好。 我们知道爬取公众号的方式常见的有两种:通过搜狗搜索去获取,缺点是只能获取最新的十条推送文章。通过微信公众号的素材管...