Search code examples
pythonselenium-webdriveriframewebdrivergetelementsbyclassname

Python Selenium iframe get element


This should be easy but somehow I've wasted 3 weeks trying to do this. I just want to get the Bid and Ask price from this site to print.

https://www.jmbullion.com/charts/silver-prices/

The whole reason I made this account was to learn how to do this, but I just don't know what I'm missing so now I'm just going to ask. How would YOU get this elements?

from selenium import webdriver
from selenium.webdriver.common.by import By

driver = webdriver.Edge()

driver.get('https://www.jmbullion.com/charts/silver-prices/')

SilverSpot0 = driver.find_elements(By.CLASS_NAME, 'price')
SilverSpot0 = driver.switch_to.frame(SilverSpot0)

print(SilverSpot0)

Solution

  • Try the below code:

    driver.maximize_window()
    driver.get('https://www.jmbullion.com/charts/silver-prices/')
    
    iframe = driver.find_element(By.XPATH, "//div[@class='content3col']//iframe")
    wait(driver, 10).until(EC.frame_to_be_available_and_switch_to_it(iframe))
    
    bidSilverPrice = driver.find_element(By.XPATH, '//div[@title="bid"]/parent::div//div[2]').text
    askSilverPrice = driver.find_element(By.XPATH, '//div[@title="ask"]/parent::div//div[2]').text
    
    print(bidSilverPrice)
    print(askSilverPrice)
    

    Console Output:

    $22.52
    $22.84
    
    Process finished with exit code 0
    

    Explanation: After logging in, first switch into the iframe within which these 2 elements Bid Ask are embedded. Use the XPATH expression //div[@class='content3col']//iframe to switch to desired iframe. After that locate the desired elements and print it.