Home > Software design >  Selenium - only sometimes sends send_keys
Selenium - only sometimes sends send_keys

Time:08-11

I am attempting to make a script to log in to Facebook, navigate to a specific webpage through the search bar, and then click on the top result; however, the script does not always send keys in the search bar and instead fails. Any idea why this is happening?

Another difficulty I am having is finding the correct path to the top search result. I have tried many different By. functions such as tag name, class, and x path yet none seem to work. Would greatly appreciate some help.

from ast import Return
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time

driver = webdriver.Chrome("C:/Users/Carson/Desktop/chromedriver.exe")
driver.get("https://www.facebook.com/")


try:
    username = WebDriverWait(driver, 7).until(
    EC.presence_of_element_located((By.ID,'email')))
    
    username.send_keys("username")

    password = driver.find_element(By.ID, 'pass')
    password.send_keys("password")

    try:
        driver.find_element(By.TAG_NAME, "button").click()
        driver.find_element(By.XPATH, '/html/body/div[1]/div[1]/div[1]/div/div[2]/div[2]/div/div/div/div/div/label/input').click()

        #clicks the search key and searches by send_keys 
        search = driver.find_element(By.XPATH,'/html/body/div[1]/div[1]/div[1]/div/div[2]/div[2]/div/div/div/div/div/label/input')
        search.click()
        search.send_keys('The Village At Gracy Farms')
        search.send_keys(Keys.RETURN)
        print("nicee")
      
    except:
        print("failedddd")
        driver.quit(77)

except:
    print("failed")
    driver.quit(22)    

CodePudding user response:

The search box element on Facebook homepage is a dynamic element, so ideally to send a character sequence to the element you need to induce WebDriverWait for the element_to_be_clickable() and you can use either of the following locator strategies:

  • Using CSS_SELECTOR:

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "input[placeholder='Search Facebook'][aria-label='Search Facebook'][aria-label='Search Facebook']"))).send_keys("The Village At Gracy Farms")
    
  • Using XPATH:

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//input[@placeholder='Search Facebook' and @aria-label='Search Facebook'][@aria-expanded='true']"))).send_keys("The Village At Gracy Farms")
    
  • Note: You have to add the following imports :

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