Python Selenium, help me locate an element in a website

Viewed 176

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.

3 Answers

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
    

You can use a different xpath:

new_order = driver.find_element_by_xpath('//a[@title="New Order"]')

But I would suggest By, WebDriverWait, and expected_conditions:

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.keys import Keys
import time
driver = webdriver.Chrome('./chromedriver')
driver.get("https://www.mql5.com/en/trading")
time.sleep(5)
iframe = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.XPATH, '//iframe[@id="webTerminalHost"]')))
driver.switch_to.frame(iframe)
new_order = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, '//a[@title="New Order"]')))
new_order.click()
Related