简体   繁体   中英

Change the value of Input field and press enter using python and selenium

I am trying to collect some information from a web page by changing the value of an input field. But every time I change the value, the webpage automatically changes the value of the input box back to the default value. Here is the implementation:

driver = webdriver.Chrome()
page = driver.get("https://www.edmunds.com/cars-for-sale-by-owner/")

inputElement = driver.find_element_by_name("zip")
inputElement.clear()
inputElement = driver.find_element_by_name("zip")
inputElement.send_keys('23835')
inputElement.send_keys(Keys.ENTER)

How can I change the value and press enter to get the filtered webpage?

Update:! Solution: Change the value to null by driver.execute_script("arguments[0].setAttribute('value','')",inputElement) , then write other logic to send keys. It did not work at first, but now Its working though.

def enter_value(zipcode):
    inputElement = driver.find_element_by_name("zip")
    driver.execute_script("arguments[0].setAttribute('value','')",inputElement)
    print(inputElement.get_attribute('value'))
    inputElement.clear()
    inputElement.send_keys(zipcode)
    inputElement.send_keys(Keys.ENTER)

driver = webdriver.Chrome()
drive = driver.get("https://www.edmunds.com/cars-for-sale-by-owner/")
WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.NAME, 'zip')))

enter_value(zipcode="23831")

Please use ctrl + a then delete to clear the input field, cause .clear() seems like not working consistent.

driver = webdriver.Chrome(driver_path)
driver.maximize_window()
#driver.implicitly_wait(30)
wait = WebDriverWait(driver, 30)
driver.get("https://www.edmunds.com/cars-for-sale-by-owner/")
inputElement = wait.until(EC.visibility_of_element_located((By.NAME, "zip")))
inputElement.send_keys(Keys.CONTROL + "a")
inputElement.send_keys(Keys.DELETE)
time.sleep(2)
inputElement.send_keys('23835')

Imports:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM