html - Nokogiri 排除 HTML 类

标签 html css ruby nokogiri

我正在尝试抓取所有对我们 Facebook 群组中的帖子发表评论的人的姓名。我在本地下载了该文件,并且能够抓取评论者的姓名以及回复这些评论的人的名字。我只想要原始评论,而不是回复...似乎我必须排除 UFIReplyList 类,但我的代码仍在提取所有名称。任何帮助将不胜感激。谢谢!

require 'nokogiri'
require 'pry'

class Scraper
  @@all = []

  def get_page
    file = File.read('/Users/mark/Desktop/raffle.html')
    doc = Nokogiri::HTML(file)
    # binding.pry

    doc.css(".UFICommentContent").each do |post|
      # binding.pry
      author = post.css(".UFICommentActorName").css(":not(.UFIReplyList)").text

      @@all << author
    end

    puts @@all
  end
end

Scraper.new.get_page

最佳答案

遍历每个 .UFICommentActorName 元素的祖先,以拒绝那些包含在 .UFIReplyList 元素中的元素。

@authors_nodes = doc.css(".UFICommentActorName").reject do |node|

  # extract all ancestor class names; 
  # beware of random whitespace and multiple classes per node
  class_names = node.ancestors.map{ |a| a.attributes['class'].value rescue nil }
  class_names = class_names.compact.map{ |names| names.split(' ') }
  class_names = class_names.flatten.map(&:strip)

  # reject if .UFIReplyList found
  class_names.include?('UFIReplyList')

end

@authors_nodes.map(&:text)

关于html - Nokogiri 排除 HTML 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52063941/

相关文章:

html - 如何使 float div 容器适合 div 高度?

ruby - 如何用 Ruby 覆盖 shell 中的打印行?

javascript - 我的测试现在因 SyntaxError: Parse error (Capybara::Poltergeist::JavascriptError) 而失败

html - Phonegap,iOS 上的屏幕键盘正在转移我的内容

html - 如何更改 Bootstrap 滚动 spy 事件链接颜色

html - 我怎样才能让所有容器的高度最高?

html - Bootstrap 4 将菜单项转换为多选

ruby-on-rails - Rails 新方法在控制台中有效,在 Controller 和浏览器中失败

html - 如何从亚马逊缩放窗口获取全分辨率图像

html - 是否可以根据父级中 div 的数量调整父级中 div 的大小?