j0shyap
j0shyap

Reputation: 51

Can't locate element by xpath in selenium?

I am learning python and selenium right now by making a small script that posts birthday comments to my facebook friends. I am able to successfully login and navigate to the "friends' birthday" modal, but then I am unable to comment in the textbox.

Here is the error I am getting:

selenium.common.exceptions.NoSuchElementException: 
Message: no such element: Unable to locate element:
{"method":"xpath","selector":"//*[@id="u_i_6"]"}

I haven't had any issues finding other page elements via XPath so I am not sure what is causing the issue. I also tried finding the textbox to comment via classname, but had the same result. Can anyone offer some thoughts?

enter image description here

EDIT: forgot to paste code

from selenium import webdriver
from pynput.keyboard import Key, Controller
import time
import config
# fetch facebook password from separate file in the same directory
pw = config.secret['pw']
keyboard = Controller()

driver = webdriver.Chrome()
options = webdriver.ChromeOptions()
options.add_argument('--disable-extensions')
options.add_argument('--disable-notifications')

# navigate to facebook url
driver.get('https://facebook.com')

# input email address
email_input = driver.find_element_by_xpath('//*[@id="email"]')
email_input.send_keys(<omitted>)
# input pw
password_input = driver.find_element_by_xpath('//*[@id="pass"]')
password_input.send_keys(pw)
# click login button element
login_button = driver.find_element_by_xpath('//*[@id="u_0_b"]')
login_button.click()

home_button = driver.find_element_by_xpath('//*[@id="u_0_c"]/a')
# wait 8 seconds for browser popup before pressing esc to get out
time.sleep(8)
keyboard.press(Key.esc)

# check if there are any birthdays today
birthday_section = driver.find_element_by_xpath('//*[@id="home_birthdays"]/div/div/div/div/a/div/div/span/span[1]')
birthday_section.click()

first_comment = driver.find_element_by_xpath('//*[@id="u_i_6"]')
first_comment.send_keys('happy birthday!')
# click post button to post comment

# close browser window after actions are complete
time.sleep(5)
driver.close()

Upvotes: 0

Views: 879

Answers (1)

Svetlana Levinsohn
Svetlana Levinsohn

Reputation: 1556

It is hard to answer without the code, but here are a couple of ideas:

  1. Make sure you are using some sort of Selenium wait, implicit or explicit, so your code does not search for an element before this element appears on the page. You can add this code after driver.get() for implicit wait:
driver.implicitly_wait(5)
  1. Also, it looks like IDs are dynamic on that page, I get a different one on my FB page. Try using this xpath to find the textarea:
"//form[contains(@action, 'birthday')]//textarea"

Hope this is helpful, good luck!

Upvotes: 1

Related Questions