Python Selenium iframe get element

Question:

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)
Asked By: SinclairCode

||

Answers:

First of all youre looking for elements and that returns a list. You will not be able to switch to something. And your class locator locates more then 200 elements. Below is an example how to locate that one iframe. Youre doing the switch to iframe correctly.After the switch you should be able to look for ask and bid prices with normal locators

iframeToSwitchTo = driver.find_element(By.ID, 'easyXDM_nfusion_lib_default2462_provider')

After the switch you can look for bid and ask prices like this:

bid price:

//div[@title="bid"]/parent::div//div[2]

ask price:

//div[@title="ask"]/parent::div//div[2]

A complete script would look something like this:

from selenium import webdriver from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

driver = webdriver.Edge()

driver.get('https://www.jmbullion.com/charts/silver-prices/')
WebDriverWait(driver,5).until(EC.presence_of_element_located
((By.ID, "easyXDM_nfusion_lib_default2462_provider")))

iframeToSwitch = driver.find_element(By.ID, 'easyXDM_nfusion_lib_default2462_provider')
driver.switch_to.frame(iframeToSwitch)
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)
Answered By: Rolandas Ulevicius

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.

Answered By: Shawn