I am trying to type in the search bar as seen in the picture in Sprouts. I've tried many different iterations but cannot type in the search bar. What am i doing wrong?
Code:
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
options = webdriver.ChromeOptions()
website = webdriver.Chrome(executable_path='/Users/myPath/chromedriver',options = options)
sprouts = {"url" : "https://shop.sprouts.com/"}
website.get(sprouts['url'])
search_bar = website.find_element(By.CSS_SELECTOR,"css-4hd4ug")
search_bar.send_keys("bananas")
search_bar.send_keys(Keys.RETURN)
CodePudding user response:
First of all, the syntax for selecting a class would be using a dot (.) before the class name, so:
.css-4hd4ug
second, there are multiple of that class, so, instead I'd go for this CSS selector copied straight from chrome #sticky-react-header > div > div.css-q1n3l > div.css-c1jgn7 > form > div > input
.
Third, it takes time for the element to appear, so you should use presence_of_element_located
. See: Selenium - wait until element is present, visible and interactable
search_bar = WebDriverWait(website, 20).until(
EC.presence_of_element_located((By.CSS_SELECTOR, "#sticky-react-header > div > div.css-q1n3l > div.css-c1jgn7 > form > div > input"))
)
Using your code, it should be refactored to:
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 import webdriver
options = webdriver.ChromeOptions()
website = webdriver.Chrome()
sprouts = {"url": "https://shop.sprouts.com/"}
website.get(sprouts["url"])
search_bar = WebDriverWait(website, 20).until(
EC.presence_of_element_located(
(
By.CSS_SELECTOR,
"#sticky-react-header > div > div.css-q1n3l > div.css-c1jgn7 > form > div > input",
)
)
)
search_bar.click()
search_bar.send_keys("bananas")
CodePudding user response:
You can enter the value in Search bar using the below XPATH:
search_bar = website.find_element(By.XPATH,".//*[@class='css-1nxa74h']/input")
Or using the below CSS_SELECTOR:
search_bar = website.find_element(By.CSS_SELECTOR,".css-1nxa74h input")