0

Following is the code which im trying to run

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import os
import time

#Create a new firefox session
browser=webdriver.Firefox()
browser.maximize_window()


#navigate to app's homepage
browser.get('http://demo.magentocommerce.com/')

#get searchbox and clear and enter details.
browser.find_element_by_css_selector("a[href='/search']").click()
search=browser.find_element_by_class_name('search-input')

search.click()
time.sleep(5)
search.click()
search.send_keys('phones'+Keys.RETURN)

However, im unable to submit the phones using send_keys. Am i going wrong somewhere?

Secondly is it possible to always use x-path to locate an element and not rely on id/class/css-selections etc ?

0

1 Answer 1

1

The input element you are interested in has the search_query class name. To make it work without using hardcoded time.sleep() delays, use an Explicit Wait and wait for the search input element to be visible before sending keys to it. Working code:

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

browser = webdriver.Firefox()
browser.maximize_window()
wait = WebDriverWait(browser, 10)

browser.get('http://demo.magentocommerce.com/')

browser.find_element_by_css_selector("a[href='/search']").click()

search = wait.until(EC.visibility_of_element_located((By.CLASS_NAME, "search-query")))
search.send_keys("phones" + Keys.RETURN)
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks!! This works as expected. Could you explain the working of the last two lines ?
@abhisheknair the line before the last one is the key to the solution here - it both waits for the element matching a locator to become visible (make sure you follow the link to the docs and understand this part) and returns it. Then, we send the search query to the located input element and the RETURN which submits the form in our case. Hope that clears things up.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.