Home > Enterprise >  Python Selenium: If there are multiple "div" tags, how do print a specific one WITHOUT Xpa
Python Selenium: If there are multiple "div" tags, how do print a specific one WITHOUT Xpa

Time:01-02

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"  onclick="streaming();" src="/video/stream?cntId=21671&amp;quality=sd"></video>
   <div></div>
   <div  tabindex="-1" style="background-image: url(&quot;https://[REDACTED].com/images/V15064/720X480/720x480/nt/4.jpg&quot;);"></div>
   <div  aria-live="assertive" aria-atomic="true"></div>
   <div  dir="ltr"></div>

Screenshot of HTML

CodePudding user response:

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'))

CodePudding user response:

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)
  • Related