Joe T. Boka
Joe T. Boka

Reputation: 6589

Locating image src and alt in a specific class with Selenium Python

I am trying to find image alt and src on a webpage. But, I am only interested in the image alt and src in a certain class. I don't want to locate images in other classes.

Here is the html:

<div class="the class I want">
    <img alt="this is the alt I need" src="https://somesite.com/images/image.jpg" width="200" height="200">
</div>

Below is a Selenium code that works to locate all the images on the page; but, as I mentioned, I only need the images in one particular class.

driver = webdriver.Firefox()
driver.get('https://www.somesite.com/somepage')
image_elements = driver.find_elements_by_xpath("//img")

for image in image_elements:
    img_src = image.get_attribute("src")
    alt = image.get_attribute("alt")

I am trying to locate the images in the class="the class I want" only.

Here is what I tried:

image_elements = driver.find_elements_by_xpath("//div[contains(@class, 'the class I want')]")

and...

image_elements = driver.find_elements_by_css_selector("div.the.class.I.want")

Also, please note that the class name contains spaces, as indicated above.

Upvotes: 1

Views: 5028

Answers (1)

Andersson
Andersson

Reputation: 52665

Try below line:

image_elements = driver.find_elements_by_xpath("//div[@class='the class I want']/img")

This should return only images that are children of div with required @class

Upvotes: 3

Related Questions