Python Selenium, help me locate an element in a website

Issue

I want to click on "new order" icon in mt4 web terminal using selenium module in python

This is the code:

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
driver = webdriver.Chrome('./chromedriver')
driver.get("https://www.mql5.com/en/trading")
new_order = driver.find_element_by_xpath('/html/body/div[3]/div[1]/a[1]/span[1]')
new_order.click()

And this is the error that I get:

selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"/html/body/div[3]/div[1]/a[1]/span[1]"}
(Session info: chrome=86.0.4240.198)

What is the correct way to locate that button, I searched and found some ways to locate elements for selenium but I couldn’t get any of them work for me.

Solution

The element with tooltip as New Order is within an <iframe> so you have to:

  • Induce WebDriverWait for the desired frame to be available and switch to it.

  • Induce WebDriverWait for the desired element to be clickable.

  • You can use the following based Locator Strategies:

    driver.get('https://www.mql5.com/en/trading')
    WebDriverWait(driver, 20).until(EC.frame_to_be_available_and_switch_to_it((By.XPATH,"//iframe[@id='webTerminalHost']")))
    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//div[text()='Connect to an Account']//following-sibling::div[1]/span"))).click()
    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//a[@title='New Order']/span"))).click()
    
  • Note : You have to add the following imports :

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

Answered By – DebanjanB

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published