Home > Net >  How to click on a specific onclick valueusing Selenium and Python
How to click on a specific onclick valueusing Selenium and Python

Time:12-11

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()

CodePudding user response:

To click on the element with text as Ikenberry Dining Center (IKE) you need to induce eatsmart

CodePudding user response:

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
  • Related