Search code examples
rubyseleniumalt

Selenium in Ruby. How can I get the text in alt attribute in img tag?


I am working on the scraping project and I am facing the big problem that I can't get the text "alt" in "img" tag.

the code is looking like this.

  <div class="example">
    <span class="on"> 
       <img src="https://www.~~~~~~~~" alt="hello">
    </span>
    <span class="on"> 
       <img src="https://www.~~~~~~~~" alt="goodbye">
    </span>
    <span class="on"> 
       <img src="https://www.~~~~~~~~" alt="konichiwa">
    </span>
  </div>

what I have tried are these

def fetch_text_in_on_class
    # @driver.find_elements(:class_name, 'on')[2].text      or this ↓
    # @driver.find_elements(:css, 'div.pc-only:nth-of-type(3) tr:nth-of-type(3)').first.text
end

also something like this

def fetch_text_in_on_class
        e = @driver.find_elements(:class => 'on').first&.attribute("alt")
        e
end

there are bunch of elements that have "on" class in a page, and I want to get all of them.

apparently I can get the elements that have "on" class with the code below but I can't get the text in alt.

@driver.find_elements(:class => 'on')

I would really appreciate if you could help me. Thank you.


Solution

  • Forgive me if my ruby syntax is incorrect or I'm not answering your actual question -- you want the alt text itself?. What if you identify the elements with class of "on" as an array, then loop through to retrieve the related alt text. So, something like this?

    elements = @driver.find_elements(:css => 'span.on > img')
    elements.each { |element|
        altText = element.attribute("alt")
    
        #whatever you want to do with the alt text, or store as an array above etc
    
    }