Search code examples
python-3.xselenium-webdriverxpathcss-selectorswebdriverwait

How to select a checkbox element with xpath?


I can fill Username/E-Mail and password but I can't click on a checkbox for personal security.

I have marked the problematic checkbox here:

enter image description here

Website: https://www.trendyol.com/uyelik

Below is what i have tried so far:

from xml.etree.ElementPath import xpath_tokenizer
from selenium import webdriver
import requests

from selenium.webdriver.common.keys import Keys
import time
import random

def start():
    driver = webdriver.Chrome()
    driver.implicitly_wait(3)
    driver.get ('https://www.trendyol.com/uyelik')
    input('Harf gir.')
    mail = driver.find_element("xpath",'//*[@id="register-email"]')
    mail.send_keys("[email protected]")
    time.sleep(0.5)
    password = driver.find_element("xpath",'//*[@id="register-password-input"]')
    time.sleep(0.5)
    password.send_keys("Emrah6161")
    male = driver.find_element ("xpath",'//*[@id="login-register"]/div[3]/div[1]/form/div[3]/div/button[2]')
    male.click()
    time.sleep(0.5)
    c1=driver.find_element ("xpath",'//*[@id="login-register"]/div[3]/div[1]/form/div[5]/div/div[1]/div/svg')
    c2=driver.find_element ("xpath",'//*[@id="login-register"]/div[3]/div[1]/form/div[6]/div/div[1]/div/svg')
    time.sleep(0.5)
    c1.click()
    c2.click()
    time.sleep(0.5)
    onay=driver.find_element ("xpath",'//*[@id="login-register"]/div[3]/div[1]/form/button')
    onay.click()
    time.sleep(20) 
start()

I tryed copying div's xpath and used click function but its not working.


Solution

  • To click on the clickable element related to marketing-email you need to induce WebDriverWait for the element_to_be_clickable() and you can use either of the following locator strategies:

    • Using CSS_SELECTOR:

      driver.get('https://www.trendyol.com/uyelik')
      WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "button#onetrust-accept-btn-handler"))).click()
      driver.find_element(By.CSS_SELECTOR, "div[name='marketing-email'] +svg.ty-check").click()
      
    • Using XPATH:

      driver.get('https://www.trendyol.com/uyelik')
      WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//button[@id='onetrust-accept-btn-handler']"))).click()
      driver.find_element(By.XPATH, "//div[@name='marketing-email']//following::*[local-name()='svg' and @class='ty-check']").click()
      
    • Note: You have to add the following imports :

      from selenium.webdriver.support.ui import WebDriverWait
      from selenium.webdriver.common.by import By
      from selenium.webdriver.support import expected_conditions as EC
      
    • Browser snapshot:

    marketing-email