0

What can I do to replace find_element_css_selector in Selenium Python to click on a specific onclick value

(javascript:unitsSelectUnit(1))

The browser is google chrome

browser.get("http://eatsmart.housing.illinois.edu/NetNutrition/46#")
browser.find_element_css_selector("a[onclick*=javascript:unitsSelectUnit(1);]").click()
html = browser.page_source
time.sleep(2)
print(html)

# close web browser
browser.close()
cruisepandey
  • 28,520
  • 6
  • 20
  • 38
aryan
  • 21
  • 6

2 Answers2

2

To click on the element with text as Ikenberry Dining Center (IKE) you need to induce WebDriverWait for the element_to_be_clickable() and you can use either of the following Locator Strategies:

  • Using LINK_TEXT:

    driver.get("http://eatsmart.housing.illinois.edu/NetNutrition/46#")
    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.LINK_TEXT, "New"))).click()
    
  • Using CSS_SELECTOR:

    driver.get("http://eatsmart.housing.illinois.edu/NetNutrition/46#")
    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "a[onclick*='unitsSelectUnit(1)']"))).click()
    
  • Using XPATH:

    driver.get("http://eatsmart.housing.illinois.edu/NetNutrition/46#")
    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//a[contains(@onclick, 'unitsSelectUnit(1)')]"))).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:

eatsmart

undetected Selenium
  • 183,867
  • 41
  • 278
  • 352
1

This CSS_SELECTOR

a[onclick*=javascript:unitsSelectUnit(1);]

that you are using in your code is wrong. Basically, you are missing ''

CSS_SELECTOR follow the below syntax:

node_name[attribute_name = 'attribute_value']

You can cross verify as well by following the below steps:

Steps to check:

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

This a[onclick*=javascript:unitsSelectUnit(1);] won't match anything, where as a[onclick*='javascript:unitsSelectUnit(1);'] will match Ikenberry Dining Center (IKE) node.

Now If you want to click on it, please use the below code:

Code:

browser.maximize_window()
wait = WebDriverWait(browser, 30)
browser.get("http://eatsmart.housing.illinois.edu/NetNutrition/46#")


try:
    btn = wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "a[onclick*='javascript:unitsSelectUnit(1);']")))
    btn.click()
except:
    print("Could not click on button")
    pass

Imports:

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
cruisepandey
  • 28,520
  • 6
  • 20
  • 38