찾다
백엔드 개발파이썬 튜토리얼python中django框架通过正则搜索页面上email地址的方法

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

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

성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
파이썬 어레이에 어떤 데이터 유형을 저장할 수 있습니까?파이썬 어레이에 어떤 데이터 유형을 저장할 수 있습니까?Apr 27, 2025 am 12:11 AM

PythonlistsCanstoreAnyDatAtype, ArrayModuLearRaysStoreOneType 및 NUMPYARRAYSAREFORNUMERICALPUTATION.1) LISTSAREVERSATILEBUTLESSMEMORY-EFFICENT.2) ARRAYMODUERRAYRAYRAYSARRYSARESARESARESARESARESARESAREDOREDORY-UNFICEDONOUNEOUSDATA.3) NumpyArraysUraysOrcepperperperperperperperperperperperperperperperferperferperferferpercient

파이썬 어레이에 잘못된 데이터 유형의 값을 저장하려고하면 어떻게됩니까?파이썬 어레이에 잘못된 데이터 유형의 값을 저장하려고하면 어떻게됩니까?Apr 27, 2025 am 12:10 AM

whenyouattempttoreavalueofthewrongdatatypeinapythonaphonarray, thisiSdueTotheArrayModule의 stricttyPeenforcement, theAllElementStobeofthesAmetypecified bythetypecode.forperformancersassion, arraysaremoreficats the thraysaremoreficats thetheperfication the thraysaremorefications는

Python Standard Library의 일부는 무엇입니까? 목록 또는 배열은 무엇입니까?Python Standard Library의 일부는 무엇입니까? 목록 또는 배열은 무엇입니까?Apr 27, 2025 am 12:03 AM

Pythonlistsarepartoftsandardlardlibrary, whileraysarenot.listsarebuilt-in, 다재다능하고, 수집 할 수있는 반면, arraysarreprovidedByTearRaymoduledlesscommonlyusedDuetolimitedFunctionality.

스크립트가 잘못된 파이썬 버전으로 실행되는지 확인해야합니까?스크립트가 잘못된 파이썬 버전으로 실행되는지 확인해야합니까?Apr 27, 2025 am 12:01 AM

thescriptIsrunningwithHongpyThonversionDueCorRectDefaultTerpretersEttings.tofixThis : 1) checktheDefaultPyThonVersionUsingPyThon-VersionorPyThon3- version.2) usvirtual-ErondmentsBythePython.9-Mvenvmyenv, 활성화, 및 파괴

파이썬 어레이에서 수행 할 수있는 일반적인 작업은 무엇입니까?파이썬 어레이에서 수행 할 수있는 일반적인 작업은 무엇입니까?Apr 26, 2025 am 12:22 AM

PythonArraysSupportVariousOperations : 1) SlicingExtractsSubsets, 2) 추가/확장 어드먼트, 3) 삽입 값 삽입 ATSpecificPositions, 4) retingdeletesElements, 5) 분류/ReversingChangesOrder 및 6) ListsompectionScreateNewListSbasedOnsistin

어떤 유형의 응용 프로그램에서 Numpy Array가 일반적으로 사용됩니까?어떤 유형의 응용 프로그램에서 Numpy Array가 일반적으로 사용됩니까?Apr 26, 2025 am 12:13 AM

NumpyArraysareSentialplosplicationSefficationSefficientNumericalcomputationsanddatamanipulation. Theyarcrucialindatascience, MachineLearning, Physics, Engineering 및 Financeduetotheiribility에 대한 handlarge-scaledataefficivally. forexample, Infinancialanyaly

파이썬의 목록 위의 배열을 언제 사용 하시겠습니까?파이썬의 목록 위의 배열을 언제 사용 하시겠습니까?Apr 26, 2025 am 12:12 AM

UseanArray.ArrayOveralistInpyThonWhendealingwithhomogeneousData, Performance-CriticalCode, OrinterFacingwithCcode.1) HomogeneousData : ArraysSaveMemorywithtypepletement.2) Performance-CriticalCode : arraysofferbetterporcomanceFornumericalOperations.3) Interf

모든 목록 작업은 배열에 의해 지원됩니까? 왜 또는 왜 그렇지 않습니까?모든 목록 작업은 배열에 의해 지원됩니까? 왜 또는 왜 그렇지 않습니까?Apr 26, 2025 am 12:05 AM

아니요, NOTALLLISTOPERATIONARESUPPORTEDBYARRARES, andVICEVERSA.1) ArraySDONOTSUPPORTDYNAMICOPERATIONSLIKEPENDORINSERTWITHUTRESIGING, WHITHIMPACTSPERFORMANCE.2) ListSDONOTEECONSTANTTIMECOMPLEXITEFORDITITICCESSLIKEARRAYSDO.

See all articles

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

Video Face Swap

Video Face Swap

완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

뜨거운 도구

안전한 시험 브라우저

안전한 시험 브라우저

안전한 시험 브라우저는 온라인 시험을 안전하게 치르기 위한 보안 브라우저 환경입니다. 이 소프트웨어는 모든 컴퓨터를 안전한 워크스테이션으로 바꿔줍니다. 이는 모든 유틸리티에 대한 액세스를 제어하고 학생들이 승인되지 않은 리소스를 사용하는 것을 방지합니다.

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

Eclipse용 SAP NetWeaver 서버 어댑터

Eclipse용 SAP NetWeaver 서버 어댑터

Eclipse를 SAP NetWeaver 애플리케이션 서버와 통합합니다.

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.

에디트플러스 중국어 크랙 버전

에디트플러스 중국어 크랙 버전

작은 크기, 구문 강조, 코드 프롬프트 기능을 지원하지 않음