You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Ruby on Rails爬虫项目:用Nokogiri按样式移除指定HTML节点

移除.story下最后一个黄色背景的p标签解决方案

在Ruby on Rails爬虫项目中,使用Nokogiri处理HTML是最可靠的方式,以下是针对你的需求的可行代码方案:

核心实现代码

require 'nokogiri'
require 'faraday'

# 获取目标页面HTML内容
url = "https://www.livelaw.in/top-stories/supreme-court-civil-suit-maintainable-jurisdiction-scope-sau-rajani-vs-sau-smita-2022-livelaw-sc-702-207475?infinitescroll=1"
response = Faraday.get(url)
doc = Nokogiri::HTML(response.body)

# 定位.story容器下的所有p标签
story_paragraphs = doc.css('.story p')

# 筛选出带有黄色背景(rgb(255,255,0))的p标签
yellow_bg_paragraphs = story_paragraphs.select do |p|
  # 先判断style属性存在,避免nil调用include?报错
  p['style']&.include?('background-color:rgb(255,255,0)')
end

# 移除最后一个符合条件的p标签(如果存在)
yellow_bg_paragraphs.last.remove unless yellow_bg_paragraphs.empty?

# 可选:输出处理后的.story下所有p标签文本,验证结果
puts doc.css('.story p').map(&:text)

关键说明

  • 筛选逻辑:通过select遍历所有p标签,检查style属性中是否包含目标背景色字符串,&.操作符确保当p标签没有style属性时不会抛出异常
  • 移除操作:调用Nokogiri节点的remove方法直接从DOM中删除目标节点,unless yellow_bg_paragraphs.empty?避免在无符合条件标签时报错
  • 兼容扩展:如果页面中存在简写样式(如background-color: yellow或background: rgb(255,255,0)),可扩展筛选条件:
    p['style']&.match?(/background(-color)?:\s*(rgb\(255,255,0\)|yellow)/i)
    

内容的提问来源于stack exchange,提问作者Labani Das

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 03:51:43