zackchess3
zackchess3

Reputation: 33

Python Selenium: If there are multiple "div" tags, how do print a specific one WITHOUT Xpath?

I am trying to learn how to print by tag. Cannot use find element by xpath or class. If there are 4 "div" tags, how do I print the contents of a specific one?

Desired Output:

vjs-poster

Attempt 1:

divs = driver.find_elements(By.TAG_NAME, "div")
print(divs[0])

Attempt 2:

divs = driver.find_elements(By.TAG_NAME, "div")
print(divs[0].get_attribute('class'))

HTML: (The third line says "vjs-poster" this is what I want to print.)

<video id="video_html5_api" class="vjs-tech" onclick="streaming();" src="/video/stream?cntId=21671&amp;quality=sd"></video>
   <div></div>
   <div class="vjs-poster" tabindex="-1" style="background-image: url(&quot;https://[REDACTED].com/images/V15064/720X480/720x480/nt/4.jpg&quot;);"></div>
   <div class="vjs-text-track-display vjs-hidden" aria-live="assertive" aria-atomic="true"></div>
   <div class="vjs-loading-spinner" dir="ltr"></div>

Screenshot of HTML

Upvotes: 0

Views: 782

Answers (2)

undetected Selenium
undetected Selenium

Reputation: 193058

To print the value of the class attribute vjs-poster of the second <div> you can use:

print(driver.find_elements(By.TAG_NAME, "div")[1].get_attribute('class'))

You can also use a css_selector as:

print(driver.find_element(By.CSS_SELECTOR, "video.vjs-tech#video_html5_api +div +div").get_attribute('class'))

Upvotes: 1

Prophet
Prophet

Reputation: 33353

You can try locating that element based on it class name and style or any one of them if the locator will still be unique.
You try this:

class_val = driver.find_elements(By.XPATH, "//div[contains(@style,'https://[REDACTED].com/images')").get_attribute('class')
print(class_val)

Upvotes: 0

Related Questions