Home > Net >  How to clear text field with Selenium Python
How to clear text field with Selenium Python

Time:11-26

Here's my code and what I tried so far :

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

PATH = "driver\chromedriver.exe"
driver = webdriver.Chrome(executable_path=PATH)
url = 'https://www.mergermarket.com/homepage'
driver.get(url)

deals = driver.find_element_by_xpath('//*[@id="header"]/div/div[2]/nav/ul/li[4]/a')

urldeals = deals.get_attribute("href")
driver.get(urldeals)

custom1 = driver.find_element_by_xpath('//*[@id="searchCriteriaSummary"]/div[4]/div/div[2]/div/div[1]/div[2]/div/div/div[2]/div')
custom1.click()

custom2 = driver.find_element_by_id('react-select-12-option-0')
custom2.click()
time.sleep(1)

date = driver.find_element_by_xpath('//*[@id="date-picker_from"]')
date.click()
date.send_keys('01/11/2021') 
time.sleep(1)

date2 = WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, '//*[@id="date-picker_to"]')))
date2.click()
date2.clear()
date2.send_keys("15/11/2021")

The two last paragraph is where I struggle.

I have this :

date

When I enter 01/11/2021 in the input text at the left, the website automatically write the actual date on the right (26/11/2021 right now).

I would like to clear the actual day and put my date but I cannot found how to do that. I did this code :

date2 = WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, '//*[@id="date-picker_to"]')))
date2.click()
date2.clear()
date2.send_keys("15/11/2021")

But it just write my date after the actual date :

date2

I tried several methods but always th same results. here the html code if it could help :

html

CodePudding user response:

Instead of this

date2 = WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, '//*[@id="date-picker_to"]')))
date2.click()
date2.clear()
date2.send_keys("15/11/2021")

You could trigger ctrl A and delete like this

date2 = WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, '//*[@id="date-picker_to"]')))
date2.click()
date2.send_keys(Keys.CONTROL   "a")
date2.send_keys(Keys.DELETE)
date2.send_keys("15/11/2021")

Imports:

from selenium.webdriver.common.keys import Keys

Also, In the same way, you could trigger Backspace as well.

date2 = WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, '//*[@id="date-picker_to"]')))
date2.click()
date2.sendKeys(Keys.BACK_SPACE)  
date2.send_keys("15/11/2021")

CodePudding user response:

Trigger ctrl a with:

from selenium.webdriver.common.keys import Keys

That'll delete everything first :)

  • Related