'selenium webdriver can't click on button using driver.find_element_by_css_selector

can't click on button using driver.find_element_by_css_selector

i try use this Locating Elements driver.find_element_by_css_selector driver.find_element_by_css_selector('#minicart-content-wrapper > div.block-content > div.actions-wrapper > div:nth-child(1) > div > a')

and have this code <a class="action viewcart" data-bind="attr: {href: shoppingCartUrl}" href="https:..." data-uw-styling-context="true" data-uw-rm-brl="false"> <span data-bind="i18n: 'View and Edit Cart'" data-uw-styling-context="true">View Cart</span> </a>

i try use the x_path //*[@id="minicart-content-wrapper"]/div[2]/div[5]/div[1]/div/a but it not working



Solution 1:[1]

Please check in the dev tools (Google chrome) if we have unique entry in HTML-DOM or not.

xpath that you should check :

//a[contains(.,'View Cart')]

Steps to check:

Press F12 in Chrome -> go to element section -> do a CTRL + F -> then paste the xpath and see, if your desired element is getting highlighted with 1/1 matching node.

If it's a unique match then click it like below:

Code trial 1:

time.sleep(5)
driver.find_element(By.XPATH, "//a[contains(.,'View Cart')]").click()

Code trial 2:

WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//a[contains(.,'View Cart')]"))).click()

Imports:

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

Code trial 2 is recommended.

Solution 2:[2]

Based on the html code provided in the query, the below locator strategies should work:

By CLASS_NAME:

driver.find_element(By.CLASS_NAME, 'action viewcart'])

By CSS_SELECTOR:

driver.find_element(By.CSS_SELECTOR, '.action viewcart'])
OR
driver.find_element(By.CSS_SELECTOR, "a[class='action viewcart']")

By XPATH (with text):

driver.find_element(By.XPATH, "//*[text()='View Cart']")

By LINK_TEXT:

driver.find_element(By.LINK_TEXT, 'View Cart'])

By XPATH (with contains):

driver.find_element(By.XPATH, "//span[contains(text(), 'View and Edit Cart')"])

Advise you to use explict wait such as WebdriverWait in order to wait until the element is visible/clickable, etc.

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 cruisepandey
Solution 2