0

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.

Abel
  • 113
  • 2
  • 9
  • Does this answer your question? [Selenium-Webdriver: Get attributes after finding an element](https://stackoverflow.com/questions/14288917/selenium-webdriver-get-attributes-after-finding-an-element) – JeffC May 10 '21 at 03:18
  • Thank you for noting. I have tried the code I found "element_class_attribute = el.attribute("class")" but I can't get the text. Any errors occur so probably I got any elements. also, I can get the name of class by using xpath but the page has a bunch of elements I want to get. so I though I cannot use xpath. – Abel May 10 '21 at 04:57

3 Answers3

1

It looks like the problem is that you are trying to get the alt text from the element with the class on. Given your posted HTML that element doesn't have the alt attribute. Try the CSS selector span.on > img to get the IMG tag and then get the alt text. An updated version of your code to get the text of the first element should work.

e = @driver.find_elements(:css => 'span.on > img').first&.attribute("alt")
JeffC
  • 22,180
  • 5
  • 32
  • 55
1

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

}
C. Peck
  • 3,641
  • 3
  • 19
  • 36
1

Let's iterate over the collection and save the text in an array and then let's print it

elements = driver.find_elements(:css => 'span.on > img').map { |element| element.attribute("alt") }

p elements

Output

["hello", "goodbye", "konichiwa"]
Rajagopalan
  • 5,465
  • 2
  • 11
  • 29