Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Selenium send keys only sending one character

I am trying to write a program that will gather data from Google Flights for different locations and times. The code below is able to clear and fill in one character for the origin of a trip, but I cannot get it to fill in the whole string:

from selenium import webdriver
import time

def find_flights(origin, destination):
    driver = webdriver.Chrome(executable_path="C:\WebDrivers\chromedriver 89\chromedriver.exe")
    driver.get("https://www.google.com/travel/flights")

    time.sleep(4)
    from_form = driver.find_element_by_xpath('//*[@id="i6"]/div[1]/div/div/div[1]/div/div/input')
    from_form.clear()
    from_form.send_keys(origin)

find_flights("Los Angeles", "New York")

In this case, the form for the origin would only contain "L" rather than "Los Angeles". I figured splitting up the string and providing a time gap between letters might fix it, like so:

def find_flights(origin, destination):
    driver = webdriver.Chrome(executable_path="C:\WebDrivers\chromedriver 89\chromedriver.exe")
    driver.get("https://www.google.com/travel/flights")

    time.sleep(4)
    from_form = driver.find_element_by_xpath('//*[@id="i6"]/div[1]/div/div/div[1]/div/div/input')
    from_form.clear()
    
    origin_split = list(origin)
    for letter in origin_split:
        driver.find_element_by_xpath('//*[@id="i6"]/div[1]/div/div/div[1]/div/div/input').send_keys(letter)
        time.sleep(0.5)

find_flights("Los Angeles", "New York")

This still only fills in the first letter. Any solutions would be appreciated!

like image 960
llamallama101092030 Avatar asked May 25 '26 03:05

llamallama101092030


1 Answers

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


def find_flights(origin, destination):
    driver = webdriver.Chrome()
    driver.get("https://www.google.com/travel/flights")
    driver.switch_to.frame(0)
    WebDriverWait(driver, 10).until(EC.element_to_be_clickable(
        (By.XPATH, '//*[contains(text(),"I agree")]'))).click()
    driver.switch_to.default_content
    from_form = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, '//*[@id="i6"]/div[1]/div/div/div[1]/div/div/input')))
    time.sleep(3)
    from_form.clear()
    from_form.click()
    from_form.send_keys(origin)


find_flights("Los Angeles", "New York")

input()

click the field before using sendkeys

install selenium 4 and you can remove that time.sleep(3) before clearing

  pip install selenium==4.0.0a7
like image 96
PDHide Avatar answered May 27 '26 16:05

PDHide