pythongoogle-chromeselenium-webdriverbrowserautomation

Why my browser is closing automatically before execute entire selenium code?


I'm studying web automation with python and selenium and created a code to insert a value in a input text.

Here's my code:

from selenium import webdriver
from selenium.webdriver.common.by import By
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.chrome.service import Service

service = Service(ChromeDriverManager().install())
driver = webdriver.Chrome(service=service)

driver.get("https://www.google.com/")
input = driver.find_element(By.XPATH, "//*[@id='APjFqb']")

input.send_keys("Test")

The code should open the browser and insert "Test" on the input, however the page closes before set the value.

Same thing happened with Safari.


Solution

  • You probably shouldn't be using input, as that is a reserved method in Python.

    You probably shouldn't be using ChromeDriverManager either, as selenium now includes Selenium Manager with it.

    And that looks like an autogenerated selector, which means it may change every time you load that page. Use (By.CSS_SELECTOR, '[name="q"]') instead on the Google page.

    If you want your script to stop at the end of your test, put in a breakpoint() on the last line. To continue from the program when stopped at a breakpoint, type c and press Enter.

    Here's everything together:

    from selenium import webdriver
    from selenium.webdriver.common.by import By
    driver = webdriver.Chrome()
    
    driver.get("https://google.com")
    search_bar = driver.find_element(By.CSS_SELECTOR, '[name="q"]')
    search_bar.send_keys("selenium github")
    search_bar.submit()
    breakpoint()
    driver.quit()
    

    For more reliability, you could use WebDriverWait to wait for elements before interacting with them. More info: https://www.selenium.dev/documentation/webdriver/waits/