'Using playwright for python, how can I click a button?
First time using playwright. Trying to log in to Pinterest.
browser = playwright.chromium.launch(headless=False)
context = browser.new_context()
page = context.new_page()
page.goto('https://pinterest.co.uk/login')
# Interact with login form
page.fill('input[name="id"]', email)
page.fill('input[name="password"]', password)
# looking for the login button. This part breaks.
page.locator('xpath=//*[@id="__PWS_ROOT__"]/div[1]/div/div[2]/div/div/div/div/div/div[4]/form/div[5]/button').click()
#open the form to create a pin
page.goto('https://www.pinterest.co.uk/pin-builder/')
I get a timeout error because it's waiting for the selector with the given xpath, but it's probably not finding it. Any ideas?
Solution 1:[1]
You should be able to get that button by text:
page.locator('"Log in"').click()
Solution 2:[2]
Try this one hope it will work for your machine too.
you cannot use xpath in all the places it leads to some unwanted errors anytime so use has-text
from playwright.sync_api import Playwright, sync_playwright, expect
def run(playwright: Playwright) -> None:
browser = playwright.chromium.launch(headless=False)
context = browser.new_context()
# Open new page
page = context.new_page()
# Go to https://www.pinterest.co.uk/login/
page.goto("https://www.pinterest.co.uk/login/")
# Click [placeholder="Email"]
page.locator("[placeholder=\"Email\"]").click()
# Fill [placeholder="Email"]
page.locator("[placeholder=\"Email\"]").fill("[email protected]")
# Click [placeholder="Password"]
page.locator("[placeholder=\"Password\"]").click()
# Fill [placeholder="Password"]
page.locator("[placeholder=\"Password\"]").fill("password")
# Click button:has-text("Log in")
# with page.expect_navigation(url="https://www.pinterest.co.uk/"):
with page.expect_navigation():
page.locator("button:has-text(\"Log in\")").click()
# ---------------------
context.close()
browser.close()
with sync_playwright() as playwright:
run(playwright)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | hardkoded |
| Solution 2 |
