Selenium can be inconsistent when it comes to sending send_keys

I'm currently working on a script to login to Facebook, search for a specific webpage using the search bar, and select the top result. However, there seems to be an issue with the script not always sending keys to the search bar and failing instead. Any insights on why this might be happening?

Additionally, I'm struggling to identify the correct path to the top search result. I've experimented with various By functions such as tag name, class, and x-path, but none of them seem to work effectively. Any assistance would be greatly appreciated.

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 performs search using 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("Nice!")

    except:
        print("Failed")
        driver.quit(77)

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

Answer №1

The search bar element on the homepage of Facebook is dynamic in nature. To input a character sequence into this element, it is recommended to utilize WebDriverWait for the element to be clickable and you can implement one 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 will need to include 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
    

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Mastering the use of getText() in Protractor with Page Object Model in Javascript

Having trouble retrieving specific values from my page object. The getText() method is returning the entire object instead of just the text, likely due to it being a Promise. I can provide my code if necessary, but I'm aiming to achieve something sim ...

Does AngularJS have a feature similar to jQuery.active?

As I utilize selenium to conduct tests on my application, I am encountering numerous ajax calls that utilize $resource or $http. It would be convenient if there was a method in angular to monitor active ajax requests so that selenium could wait until they ...

Is there a way to find the JavaScript Window ID for my current window in order to utilize it with the select_window() function in

I'm currently attempting to choose a recently opened window while utilizing Selenium, and the select_window() method necessitates its WindowID. Although I have explored using the window's title as recommended by other sources, and enabled Seleni ...

Selenium Assistance: I'm encountering a scenario where on a webpage, two elements share the same Xpath, making it difficult to differentiate them based on even

At index [1], both elements are identified, but at index [2], nothing is identified. The key difference between the two is that one has display:none, and the other has display:block. However, their involvement in determining these fields is minimal due to ...

Retrieve the content of the specified element within the webpage

How can I modify the method to successfully retrieve the text content of an element on a webpage using Selenium with JavaScript? Currently, it is returning undefined. homepage.js const { Builder, By, Key, until } = require('selenium-webdriver'); ...

Having trouble with accessing an element that contains both onclick and text attributes in Selenium Webdriver?

The HTML code I'm dealing with includes this element: <a style="text-decoration:none; font-weight:normal;" href="javascript:void(0);" onclick="CreateNewServiceItemApproved();"> <img src="icons/ui/addnew.png"> <span style="color:# ...

Steps for creating an HTML report using Intern JS

Our team relies on intern JS for automating functional tests, however we are facing difficulty in generating an html report. I attempted to use locvhtml as suggested by the Intern documentation (https://theintern.github.io/intern/#reporter-lcov), but unfo ...

A guide on extracting the text content from an anchor tag by using xPath() with a combination of selenium and Mocha

I have successfully chosen an <a> tag. My goal is to display the text of the anchor tag, but I am facing difficulties. The technologies being used are selenium, mocha, javascript, and phantomJS This is the detailed script: var assert = require(&ap ...

Executing a JavaScript code in a Python webdriver: A step-by-step guide

Using Selenium 2 Python webdriver: I encountered an issue where I needed to click on a hidden element due to a hover effect. In search of solutions to unhide and select the element, I came across the following examples: Example in Java: JavascriptExecut ...

Invoke a Python function from JavaScript

As I ask this question, I acknowledge that it may have been asked many times before. If I missed the answers due to my ignorance, I apologize. I have a hosting plan that restricts me from installing Django, which provided a convenient way to set up a REST ...

Troubleshooting Timeout Problems with Selebiun Crawler in C#

I am encountering an error while running the following code. public void GetCategoriesSelenium() { string javascript = System.IO.File.ReadAllText(@"GetCategory.js"); CrawlerWebSeleniumJS.ExecuteScript("var finished;"); ...

What is the best way to duplicate an entire webpage with all its content intact?

Is it possible to copy an entire page including images and CSS using Selenium? Traditional methods like ctrl + a or dragging the mouse over the page do not seem to work. How can this be achieved with Selenium without requiring an element to interact with? ...

How to access a Selenium element using JavaScriptExecutor

My task involves working with a collection of elements in Selenium, specifically located using the By.CssSelector method: var contentRows = new List<TableRow>(); for (var i = 1; i < PositiveInfinity; i++) { var cssSelectorToFind = $"tbody &g ...

Is it possible to access a hidden JavaScript variable in Selenium?

Is there a way to extract the array "o" that contains data used for drawing a polygon? Simply using driver.execute("return o") or console.log doesn't seem to work. Any suggestions on how to achieve this? const zt = function(e, t, n, r) { c ...

Guide on setting an attribute value with JavaScriptExecutor in Selenium WebDriver

I am attempting to set an attribute value for all instances of the same type of <img> tag on My website, for example: <img src="images/temp/advertisement.png"> and I want to set style="display: none" so that I can hide them. I have tried the ...

Interacting with shadow DOM elements using Selenium's JavaScriptExecutor in Polymer applications

Having trouble accessing the 'shop now' button in the Men's Outerwear section of the website with the given code on Chrome Browser (V51)'s JavaScript console: document.querySelector('shop-app').shadowRoot.querySelector ...

Button click event is not being triggered by Ajax rendering

I am facing an issue with my Django template that showcases scheduled classes for our training department. Each item in the list has a roster button which, when clicked, should display the class roster in a div. This functionality works perfectly. However, ...

Can you explain the meaning of arguments[0] and arguments[1] in relation to the executeScript method within the JavascriptExecutor interface in Selenium WebDriver?

When utilizing the executeScript() method from the JavascriptExecutor interface in Selenium WebDriver, what do arguments[0] and arguments[1] signify? Additionally, what is the function of arguments[0] in the following code snippet. javaScriptExecutor.ex ...

Encountering an Issue Executing Selenium Test on jQuery v2.0.2 and Play Framework

While I may not be a selenium expert, it seems that I've stumbled upon a bug when trying to utilize jQuery v2.0.2 with my Play Framework 2.2.1 application instead of the default jQuery v.1.9.0. Whenever I run "play test", I encounter the following err ...

What is the process for establishing a dependency on two distinct JavaScript files, similar to the depends-on feature found in TestNG?

I am faced with a scenario where I have two separate JS files containing test methods, namely File1 and File2. The requirement is that File2.js should only be executed if File1.js has successfully completed its execution. My current setup involves using ...