【问题标题】:Getting all unique URL's using nokogiri使用 nokogiri 获取所有唯一 URL
【发布时间】:2017-12-03 17:45:39
【问题描述】:

我一直在努力尝试使用 .uniq 方法从网站(在 /informatics 路径内)生成唯一的 URL 列表。无论我尝试什么,在尝试生成列表时都会出现方法错误。我确定这是语法问题,我希望有人能指出我正确的方向。

获得列表后,我需要通过 ActiveRecord 将它们存储到数据库中,但我需要唯一的列表,然后才能开始解决这个问题。

require 'nokogiri'
require 'open-uri'
require 'active_record'

ARGV[0]="https://www.nku.edu/academics/informatics.html"

ARGV.each do |arg|
  open(arg) do |f|
    # Display connection data
    puts "#"*25 + "\nConnection: '#{arg}'\n" + "#"*25
    [:base_uri, :meta, :status, :charset, :content_encoding,
    :content_type, :last_modified].each do |method|
      puts "#{method.to_s}: #{f.send(method)}" if f.respond_to? method
    end

    # Display the href links
    base_url = /^(.*\.nku\.edu)\//.match(f.base_uri.to_s)[1]
    puts "base_url: #{base_url}"

    Nokogiri::HTML(f).css('a').each do |anchor|
      href = anchor['href']
      # Make Unique

      if href =~ /.*informatics/
        puts href
        #store stuff to active record
       end
     end
  end
end

【问题讨论】:

标签: ruby nokogiri open-uri


【解决方案1】:

替换 Nokogiri::HTML 部分以仅选择与 /*.informatics/ 匹配的那些 href 属性,然后您可以使用 uniq,因为它已经是一个数组:

require 'nokogiri'
require 'open-uri'
require 'active_record'

ARGV[0] = 'https://www.nku.edu/academics/informatics.html'

ARGV.each do |arg|
  open(arg) do |f|
    puts "#{'#' * 25} \nConnection: '#{arg}'\n #{'#' * 25}"

    %i[base_uri meta status charset content_encoding, content_type last_modified].each do |method|
      puts "#{method.to_s}: #{f.send(method)}" if f.respond_to? method
    end

    puts "base_url: #{/^(.*\.nku\.edu)\//.match(f.base_uri.to_s)[1]}"

    anchors = Nokogiri::HTML(f).css('a').select { |anchor| anchor['href'] =~ /.*informatics/ }
    puts anchors.map { |anchor| anchor['href'] }.uniq
  end
end

output

【讨论】:

  • 完美,感谢您的帮助。我已经写了一堆超级接近这个的东西,但无法得到它。真的很感激。
  • 由于您只是迭代和打印 url,您需要一种方法来检查它们是否已经打印,希望这对您有用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-09-06
  • 2019-09-02
相关资源
最近更新 更多