Home > other >  How to override the default input field value using Selenium and Python
How to override the default input field value using Selenium and Python

Time:10-25

I am using python and selenium to scrape this website and I need to override the default value in the zipcode field. I have used the .clear() method and then tried sending my own values using the send_keys() function but the default zipcode still remains in the input field. Does anyone have any idea how to go around this? Below is my code:

from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from webdriver_manager import driver
from webdriver_manager.chrome import ChromeDriverManager
radius = int(input("Enter the radius: "))
zipcode = int(input("Enter your zipcode"))

url = f'https://www.edmunds.com/cars-for-sale-by-owner/'

options = Options()
options.headless = False
options.add_experimental_option("detach", True)

browser = webdriver.Chrome(ChromeDriverManager().install(), options=options)
browser.maximize_window()
browser.get(url)
browser.set_page_load_timeout(15)

zipcode_form = browser.find_element_by_name('zip')
zipcode_form.clear() #This is meant to clear the default value in the zipcode field
zipcode_form.send_keys(str(zipcode)) #This is enter the zipcode value I provided in the zipcode field
zipcode_form.send_keys(Keys.RETURN) #I did this because there is no button to click after filling the zipcode form on the website and pressing enter works instead

... # The rest of my code which extracts the information I want

I just started learning selenium pardon me if I made any silly mistake.

CodePudding user response:

There can be multiple ways of doing this. One is using Javascript Executor defined below. "value" contains zip to be entered.

element = driver.find_element_by_name('zip')
driver.execute_script("arguments[0].value='"   value   "';", element)

CodePudding user response:

I would suggest finding the driver element by ID, as it's unique to that element:

driver.find_element_by_id('zip').clear()
  • Related