首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用Ruby的Anemone Gem刮掉网站上的所有电子邮件地址

使用Ruby的Anemone Gem刮掉网站上的所有电子邮件地址
EN

Stack Overflow用户
提问于 2017-04-20 00:29:45
回答 2查看 206关注 0票数 1

我正试图使用一个单一的文件Ruby脚本在一个给定的站点上刮取所有的电子邮件地址。在文件的底部,我有一个硬编码的测试用例,它使用的URL在特定的页面上列出了一个电子邮件地址(所以它应该在第一个循环的第一次迭代中找到一个电子邮件地址。

由于某些原因,我的正则表达式似乎不匹配:

代码语言:javascript
复制
#get_emails.rb
require 'rubygems'
require 'open-uri'
require 'nokogiri'
require 'mechanize'
require 'uri'
require 'anemone'

class GetEmails

  def initialize
      @urlCounter, @anemoneCounter  = 0
      $allUrls, $emailUrls, $emails = []
  end


  def has_email?(listingUrl)
   hasListing = false
   Anemone.crawl(listingUrl) do |anemone|
      anemone.on_every_page do |page|
      body_text = page.body.to_s
      matchOrNil = body_text.match(/\A[^@\s]+@[^@\s]+\z/)
       if matchOrNil != nil
        $emailUrls[$anemoneCounter] = listingUrl
        $emails[$anemoneCounter] = body_text.match
        $anemoneCounter += 1
        hasListing = true
      else 
      end
    end
   end
   return hasListing
  end

end 

emailGrab = GetEmails.new()
emailGrab.has_email?("http://genuinestoragesheds.com/contact/")
puts $emails[0]
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2017-04-20 02:25:50

\A\z分别在您的匹配字符串的开始和结束。显然,该网页包含的内容更多,只是一个电子邮件字符串,否则你根本不做regex测试。

您可以将其简化为仅/[^@\s]+@[^@\s]+/,但是您仍然需要清理提取电子邮件的字符串。

票数 0
EN

Stack Overflow用户

发布于 2017-04-20 16:24:41

下面是代码的工作版本。使用单个regex查找包含电子邮件的字符串,再使用三个正则表达式来清理它。

代码语言:javascript
复制
#get_emails.rb
require 'rubygems'
require 'open-uri'
require 'nokogiri'
require 'mechanize'
require 'uri'
require 'anemone'

class GetEmails

  def initialize
      @urlCounter = 0
      $anemoneCounter  = 0
      $allUrls = []
      $emailUrls = []
      $emails = []
  end

  def email_clean(email)
    email = email.gsub(/(\w+=)/,"")  
    email = email.gsub(/(\w+:)/, "")
    email = email.gsub!(/\A"|"\Z/, '')
    return email
  end


  def has_email?(listingUrl)
   hasListing = false
   Anemone.crawl(listingUrl) do |anemone|
      anemone.on_every_page do |page|
      body_text = page.body.to_s
      #matchOrNil = body_text.match(/\A[^@\s]+@[^@\s]+\z/)   
      matchOrNil = body_text.match(/[^@\s]+@[^@\s]+/)
       if matchOrNil != nil
        $emailUrls[$anemoneCounter] = listingUrl
        $emails[$anemoneCounter] = matchOrNil
        $anemoneCounter += 1
        hasListing = true
      else 
      end
    end
   end
   return hasListing
  end

end 

emailGrab = GetEmails.new()
found_email = "href=\"mailto:genuinestoragesheds@gmail.com\""
puts emailGrab.email_clean(found_email)
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/43508247

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档