簡體   English   中英

使用正則表達式抓取電子郵件時無法排除不需要的文件擴展名

[英]Unable to exclude unwanted file extensions while grabbing emails using regex

我已經使用regular expression在python中編寫了一個腳本,以從某些網站獲取電子郵件地址。 我使用硒,因為很少有網站是動態的。 但是,只要在這些頁面中沒有類似於電子郵件的文件擴展名,我的腳本就可以正常工作,例如himalayan-institute-logo@2x.png

如何在抓取電子郵件時排除以.png.jpg結尾的擴展名?

我使用過的正則表達式模式:

[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+

我正在嘗試的腳本:

import re
from selenium import webdriver

URLS = (
    'https://www.himalayaninstitute.org/about/',
    'http://www.innovaprint.com.sg/',
    'http://www.cityscape.com.sg/?page_id=37',
    'http://www.yogaville.org',
    )

def get_email(driver,link):
    driver.get(link)
    email = re.findall(r'[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+',driver.page_source)
    if email: 
        print(link,email[0])
    else: 
        print(link)

if __name__ == '__main__':
    chromeOptions = webdriver.ChromeOptions()
    chromeOptions.add_argument("--headless")
    driver = webdriver.Chrome(chrome_options=chromeOptions)
    for url in URLS:
        get_email(driver,url)
    driver.quit()

我有的輸出:

https://www.himalayaninstitute.org/about/ himalayan-institute-logo@2x.png
http://www.innovaprint.com.sg/ info@innovacoms.com
http://www.cityscape.com.sg/?page_id=37 info@cityscape.com.sg
http://www.yogaville.org Yantra-@500.png

最后一部分[a-zA-Z0-9-.]+是廣泛匹配,沒有考慮點的位置。 例如,它也可以匹配.....

一種可能是仍然使用模式的第一部分[a-zA-Z0-9_.+-]+@進行匹配,包括@符號。

然后使用正向前瞻斷言右邊的內容不以.png或.jpg結尾,並匹配點至少在1個非點字符之間的模式。

[a-zA-Z0-9_.+-]+@[a-zA-Z0-9]+(?:\.[a-zA-Z0-9]+)*(?!\.(?:png|jpg))\.[a-zA-Z0-9]+

說明

  • [a-zA-Z0-9_.+-]+@允許匹配的字符后跟@
  • [a-zA-Z0-9]+匹配角色類中列出的任何一個
  • (?:非捕獲組
    • \\.[a-zA-Z0-9]+匹配一個點,后跟1+倍字符類中列出的值
  • )*關閉非捕獲組並重復0次以上
  • (?!負向前看,斷言以下內容不是
    • \\.(?:png|jpg)匹配.png或.jog
  • )\\.[a-zA-Z0-9]+關閉並匹配1+次點和字符類中列出的內容

正則表達式演示

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM