繁体   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