Search code examples
pythonseleniumselenium-webdriverxpathpython-webbrowser

PYTHON: xPath won't locate and type in a field. Using selenium, Webdriver, etc


I have been researching xPath with selenium for the past couple days and haven't been able to find an answer to my question. I have followed some guides on how to locate a text field using 'inspect' on a webpage and then send_keys() to that field. But I am coming up with a few errors:

import webbrowser
from selenium import webdriver
driver = webdriver.Chrome

driver = webdriver.Chrome
webbrowser.open("https://www.facebook.com/")

id_box = driver.find_element_by_xpath('//*[@id="email"]')
id_box.send_keys('username')

It's responding with this error:

Traceback (most recent call last):
File "/Users/****/Library/Preferences/PyCharmCE2019.1/scratches/scratch_11.py", line 21, in <module>
id_box = driver.find_element_by_xpath('//*[@id="email"]')
TypeError: find_element_by_xpath() missing 1 required positional argument: 'xpath'

I have tried changing my code to this:

id_box = driver.find_element_by_xpath(xpath='//*[@id="email"]')

but then it gives me this error:

    id_box = driver.find_element_by_xpath(xpath='//*[@id="email"]')
    TypeError: find_element_by_xpath() missing 1 required positional argument: 'self'

I've tried everything my small brain can think of, and everything larger brains such as google has suggested. But It will not send keys or recognize the text box. I've also tried other things as find_element_by_id, or find_element_by_name, but still have no success. I tried doing a google sign in script before this, and yielded the same results.

(P.s) the link does open with webbrowser.open("https://www.facebook.com") but it doesn't do anything after that.


Solution

  • Let's start clean

    1. Install Chrome browser
    2. Install matching version of the Chromedriver
    3. Install the latest version of selenium using pip

      pip install -U selenium
      
    4. Use Explicit Wait to help Selenium to locate the element

    Example suggested code:

    from selenium import webdriver
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.support import expected_conditions as EC
    
    driver = webdriver.Chrome("c:\\path\\to\\chromedriver.exe")
    driver.maximize_window()
    driver.get("https://facebook.com")
    
    id_box = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, "//input[@id ='email']")))
    id_box.send_keys("username")
    driver.quit()