求助:如何用Ruby Nokogiri选择并打印'+ Show all 4'元素
Hey there! Let's get that '+ Show all 4' text extracted using Ruby and Nokogiri. Here's how you can do it:
Solution
First, make sure you have Nokogiri installed. If you haven't already, run this in your terminal:
gem install nokogiri
Then use this code snippet to parse your HTML and grab the target text:
require 'nokogiri' # Your HTML snippet html_content = <<~HTML <span data-plusbox-cid="8460070" href="/shopping/product/13207837492092556120/plusbox/8460070?sa=X&ved=0ahUKEwjuu-3dn5baAhXCtFMKHRg7DhoQhxoIRg" data-plusbox-state="hidden" jsaction="pdpb.tpb"> <span class="shop__a AFgVce" id="os-plusbox-show-8460070"> + Show all 4 </span> <span class="shop__a AFgVce" id="os-plusbox-hide-8460070" style="display:none">...</span></span> HTML # Parse the HTML doc = Nokogiri::HTML(html_content) # Method 1: Target by ID (most reliable since IDs are unique) show_all_text = doc.at_css('#os-plusbox-show-8460070').text.strip puts show_all_text # Outputs: "+ Show all 4" # Method 2: Fallback if the ID might change # Use class selectors combined with text content show_all_text_fallback = doc.xpath("//span[contains(text(), 'Show all')]").text.strip puts show_all_text_fallback # Same output
Quick Explanations:
at_css('#os-plusbox-show-8460070'): Grabs the exact span element using its unique ID—this is the most straightforward and reliable method..text.strip: Extracts the text inside the element and removes any extra whitespace around it, giving you clean output.- The XPath method (
//span[contains(text(), 'Show all')]) is useful if the ID isn't fixed; it finds any span element that contains the phrase "Show all" in its text.
内容的提问来源于stack exchange,提问作者DataXPH
相关产品推荐
相关产品推荐

