【问题标题】:Using Ruby's Anemone Gem to Scrape All Email Addresses From a Site使用 Ruby 的 Anemone Gem 从站点中抓取所有电子邮件地址
【发布时间】:2017-04-20 00:29:45
【问题描述】:

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

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

#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]

【问题讨论】:

  • 该 gem 必须无人维护。

标签: ruby anemone


【解决方案1】:

所以这是代码的工作版本。使用单个正则表达式来查找包含电子邮件的字符串,并使用另外三个来清理它。

#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)

【讨论】:

  • 只是想知道,为什么美元符号?
  • 创建全局变量以便能够直接从 irb 访问它们。
  • 这很有趣。
  • 我实际上遇到了一些误报的问题。例如,上面的正则表达式匹配以下作为“电子邮件地址”:“href="instagram.com/…>"
  • 用别的东西试试/\A[\w+\-.]+@[a-z\d\-]+(\.[a-z\d\-]+)*\.[a-z]+\z/i检查rubular.com
【解决方案2】:

\A\z 分别位于匹配字符串的开头和结尾。显然,该网页包含的不仅仅是一个电子邮件字符串,或者您根本不进行正则表达式测试。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-26
    • 1970-01-01
    • 2023-03-11
    • 1970-01-01
    相关资源
    最近更新 更多