python using selenium webdriver

Viewed 84

I'm trying to open the "digikey" website and use the search bar to send some data. Here's an example of the code but it looks like the send key is not working. I need help. Thank you.

import time
from openpyxl import load_workbook
from selenium import webdriver
from selenium.webdriver.common.keys import Keys

driver = webdriver.Chrome(executable_path='C:/Users/amuri/AppData/Local/Microsoft/WindowsApps/PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0/site-packages/chromedriver.exe')
driver.implicitly_wait(3)

url ='https://www.digikey.com/'
driver.get(url)
print(driver.title)
elem = driver.find_element_by_xpath("/html/body/header/div[2]/div[1]/div/div[2]/div[2]/input")
elem.click()
elem.send_keys("myString")
print(elem.text)
1 Answers

For elem use css selector, not long xpath:

elem = driver.find_element_by_css_selector("#main-layout-content .header__searchinput")

header__searchinput class is not unique, that's why I used main-layout-content id to as a parent.

Also add explicit wait:

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

wait = WebDriverWait(driver, timeout=30)
wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "#main-layout-content .header__searchinput")))
elem = driver.find_element_by_css_selector("#main-layout-content .header__searchinput")
elem.click()
elem.send_keys("myString")
Related