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

如何用Ruby Watir或JavaScript获取网页Section前5个元素并提取类名颜色?

Got it, let's tackle this problem step by step. Since your target section is dynamic (adding a new element with a color class every 30 seconds), we need solutions that handle both initial element retrieval and automatic updates. Below are working implementations using Ruby Watir and JavaScript:

1. Ruby Watir Implementation

Watir makes it straightforward to interact with dynamic web elements, and we can fix the "can't access internal elements" issue by correctly targeting child elements of the section. Here's a complete example:

require 'watir'

# Initialize browser (Chrome in this case)
browser = Watir::Browser.new(:chrome)
browser.goto('your-target-url')

# Locate the dynamic section (replace with your actual selector: id, class, etc.)
target_section = browser.section(id: 'dynamic-color-section')

# Function to extract top 5 color values
def extract_top_5_colors(section)
  # Get all elements in the section with a color class (adjust regex to match your class pattern)
  color_elements = section.elements(class: /color-.+/).first(5)
  # Extract color from class names (e.g., "color-blue" → "blue")
  color_elements.map do |elem|
    color_class = elem.classes.grep(/color-(.+)/).first
    color_class.split('-').last if color_class
  end.compact
end

# Initial extraction
puts "Initial top 5 colors: #{extract_top_5_colors(target_section).join(', ')}"

# Handle dynamic updates (check every 30 seconds)
previous_count = target_section.elements(class: /color-.+/).count
loop do
  sleep(30)
  current_count = target_section.elements(class: /color-.+/).count
  if current_count > previous_count
    puts "New element added! Updated top 5 colors: #{extract_top_5_colors(target_section).join(', ')}"
    previous_count = current_count
  end
end

# Don't forget to close the browser when done (you might want to add a stop condition)
# browser.close

Key Notes:

  • Replace 'your-target-url' and the section selector (id: 'dynamic-color-section') with your actual page details.
  • The regex /color-.+/ assumes your color classes follow a pattern like color-red, color-green — adjust this to match your exact class naming convention.
  • The loop checks for new elements every 30 seconds. For more precise detection, you could use Watir's Wait method to wait for element count changes instead of fixed sleep.
2. JavaScript Implementation

If you prefer a browser-side solution (e.g., running in the console or embedding in a userscript), JavaScript with MutationObserver is ideal for efficient dynamic element detection:

// Locate the target section (replace with your selector)
const targetSection = document.querySelector('#dynamic-color-section');

// Function to extract top 5 color values
function getTop5Colors() {
  // Get all elements in the section with a color class
  const colorElements = Array.from(targetSection.querySelectorAll('[class*="color-"]')).slice(0, 5);
  // Extract color from class names
  return colorElements.map(elem => {
    const colorClass = elem.classList.find(cls => cls.startsWith('color-'));
    return colorClass ? colorClass.split('-')[1] : null;
  }).filter(Boolean);
}

// Initial extraction
console.log('Initial top 5 colors:', getTop5Colors());

// Set up MutationObserver to detect new elements in the section
const observer = new MutationObserver((mutations) => {
  mutations.forEach(mutation => {
    // Check if new elements were added
    if (mutation.addedNodes.length > 0) {
      console.log('New element detected! Updated top 5 colors:', getTop5Colors());
    }
  });
});

// Start observing the section for child element changes
observer.observe(targetSection, { childList: true, subtree: true });

// To stop observing later: observer.disconnect();

Key Notes:

  • MutationObserver listens for real-time changes to the section's child elements, which is more efficient than polling every 30 seconds.
  • Adjust the selector [class*="color-"] and class check startsWith('color-') to match your color class pattern.
  • This can be run directly in your browser's developer console, or packaged as a userscript for persistent use.

内容的提问来源于stack exchange,提问作者Paul Heinemeyer

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 09:10:58