Log into Sites

Automating the login process is a crucial step in a workflow since it allows your script to access protected content and perform actions as an authenticated user.

Overview

This guide shows how to log into a website with AgentQL.

There are four primary steps to logging into a website:

  1. Visit the URL
  2. Query the form elements
  3. Fill out the required form fields
  4. Submit the form

Visit the page

First, you need to navigate to the page with AgentQL and Playwright:

cache_user_credentials.py
python
URL = "https://practicetestautomation.com/practice-test-login/"

with sync_playwright() as p, p.chromium.launch(headless=False) as browser:
    page = agentql.wrap(browser.new_page())  # Wrapped to access AgentQL's query API

    page.goto(URL)

Query the form elements

Next, you'll need to use the query_elements to find all of the required form elements that you'll need to interact with.

cache_user_credentials.py
python
LOGIN_QUERY = """
{
    username_field
    password_field
    submit_btn
}
"""

response = page.query_elements(LOGIN_QUERY)

Fill out required form fields

Then, you'll utilize Playwright's fill() method to fill the required login credentials in the form.

cache_user_credentials.py
python
response.username_field.fill("student")
response.password_field.fill("Password123")

Submit form

Finally, submit the login form using the click() method.

cache_user_credentials.py
python
# 4. Click the submit button
response.submit_btn.click()

Conclusion

Here is a complete script that to perform a login action with AgentQL:

cache_user_credentials.py
python
import agentql
from playwright.sync_api import sync_playwright

# Set the URL to the desired website
URL = "https://practicetestautomation.com/practice-test-login/"

LOGIN_QUERY = """
{
    username_field
    password_field
    submit_btn
}
"""

with sync_playwright() as p, p.chromium.launch(headless=False) as browser:
    page = agentql.wrap(browser.new_page())  # Wrapped to access AgentQL's query API

    # 1. Navigate to the URL
    page.goto(URL)

    # 2. Get the username and password fields
    response = page.query_elements(LOGIN_QUERY)

    # 3. Fill the username and password fields
    response.username_field.fill("student")
    response.password_field.fill("Password123")

    # 4. Click the submit button
    response.submit_btn.click()

    # Used only for demo purposes. It allows you to see the effect of the script.
    page.wait_for_timeout(10000)

Now that you know how to login to a website with AgentQL, learn how to cache and reuse those credentials in the next guide.