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和C语言混编的几种方式(推荐)

Python这些年风头一直很盛,占据了很多领域的位置,Web、大数据、人工智能、运维均有它的身影,甚至图形界面做的也很顺,乃至full-stack这个词语刚出来的时候,似乎就是为了描述它...

Python函数式编程指南(二):从函数开始

2. 从函数开始 2.1. 定义一个函数 如下定义了一个求和函数: 复制代码 代码如下: def add(x, y):     return x + y...

Python Multiprocessing多进程 使用tqdm显示进度条的实现

Python Multiprocessing多进程 使用tqdm显示进度条的实现

1.背景 在python运行一些,计算复杂度比较高的函数时,服务器端单核CPU的情况比较耗时,因此需要多CPU使用多进程加快速度 2.函数要求 笔者使用的是:pathos.multipr...

简单了解python字符串前面加r,u的含义

简单了解python字符串前面加r,u的含义

这篇文章主要介绍了简单了解python字符串前面加r,u的含义,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 u/U:表示unicod...

Django命名URL和反向解析URL实现解析

Django命名URL和反向解析URL实现解析

命名 URL: test.html: <!DOCTYPE html> <html lang="en"> <head> <meta cha...