简体   繁体   中英

Select input element by id using Selenium Python

I'm trying to click on a box that has the following HTML code:

<li>
  <input id="mce-group[166]-166-0" type="checkbox" value="1" name="group[166][1] >
  <label for="mce-group[166]-166-0">I agree</label>
</li>

I've tried it all: id, name, xpath, text,... Running something like this:

select_box = driver.find_element_by_xpath('//*[@id="mce-group[166]-166-0"]')
select_box.click()

I get this error:

selenium.common.exceptions.ElementNotInteractableException: Message: Element <input id="mce-group[166]-166-0" name="group[166][1]" type="checkbox"> could not be scrolled into view

To click on the <input> element associated with the text I agree you need to induce WebDriverWait for the element_to_be_clickable() and you can use either of the following Locator Strategies :

  • Using CSS_SELECTOR :

     WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "label[for=\"mce-group[166]-166-0\"]"))).click()
  • Using XPATH :

     WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//label[@for=\"mce-group[166]-166-0\"]"))).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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM