Reputation: 397
I'm trying to choose a checkbox from a certain website. this is a part of their HTML code.
<div class="deliveryCheckboxContainer">
<input class="deliveryCheckbox hiddenCheckbox" id="deliveryCheckbox-684" data-deliveryid="684" type="checkbox" /><label for="deliveryCheckbox-684" class=" checkbox classic"></label>
</div>
I tried a few different approaches. I either get an error saying the element isn't there or that it cannot be interacted with.
This is an example of what I tried:
browser.find_element_by_xpath('//*[@id="deliveryCheckbox-684"]').click()
Upvotes: 3
Views: 7031
Reputation: 313
Try using the time.sleep()
function to see whether it is then able to click the check box or not. If it does, then use try and except method to find if the checkbox has been loaded and then click it and move forward. As suggested above, that sleep function is not a good practice.
If the program is unable to locate the checkbox, then try navigating to it through driver.find_element_by_id
. Navigating elements by Id is by far the best technique I've ever used.
Upvotes: 0
Reputation: 9969
WebDriverWait(browser, 10).until(EC.element_to_be_clickable((By.XPATH,"//label[@for='deliveryCheckbox-684']"))).click()
You'd have induce waits for the element to be clickable and click the label tag.
Import
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
Upvotes: 0
Reputation: 4212
First, check answer above about timing issue. Second, I think that you are trying to find a dynamic id locator. Try to find by css.
browser.find_element_by_css_selector('.deliveryCheckbox.hiddenCheckbox').click()
Also, try using the xpath in the case when label
is what you really need to click:
browser.find_element_by_xpath("//label[contains(@for,'deliveryCheckbox')]")
Upvotes: 1
Reputation: 1
As far as I know, you can't click on hidden elements in selenium, and class "hiddenCheckbox" implies that it is indeed hidden. Apart from that, including errors you get and the website you are trying to scrape would make additional help possible. Currently I can only tell you to make the checkbox visible in some way.
Upvotes: 0
Reputation: 17246
It’s likely a timing issue. Many pages dynamically build DOM structure after they load.
Try adding a sleep for a second or two after loading the URL before trying to find that element. For the most robustness, you would put that in a loop and timeout after 10 seconds or so.
Upvotes: 1