1

I'd prefer to refrain from using xpaths unless it is indeed the only way to do it. Here's the simple checkbox I'm playing with: w3schools.checkbox

I want to check the "I have a bike". I tried calling the find_element_by_name method on self.driver but wihtout success and here's my miserable attempt to use xpaths:

from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException

class CheckBox:
    def __init__(self):
        self.url = 'https://www.w3schools.com/tags/tryit.asp?filename=tryhtml_input_checked'
        self.driver = webdriver.Firefox()
        self.driver.get(self.url)

    def check_I_have_a_bike(self):
        bike_xpath = ".//input[@value='Bike']" # seems pretty straightforward and simple
        try:
            self.driver.find_element_by_xpath(bike_xpath).click()
        except NoSuchElementException as e:
            print('Error: {error_message}'.format(error_message=e))

checker = CheckBox()
checker.check_I_have_a_bike()

`Error: Unable to locate element: .//input[@value='Bike']`

What do I do wrong?

1 Answer 1

1

Target input field located inside an iframe. To handle checkbox you have to switch to iframe first:

self.driver.switch_to.frame("iframeResult")
self.driver.find_element_by_xpath(bike_xpath)

It should be also accessible by name:

self.driver.find_element_by_name("vehicle")

but note that name "vehicle" applied to both checkboxes

Also you might need to use

self.driver.switch_to.default_content()

to switch back from iframe

Sign up to request clarification or add additional context in comments.

3 Comments

Hmmm it worked. Seems like I didn't play around with xpaths enough to work it out for meself. But there's no other way of doing it without first switching to the iframe, right?
iframe is another HTML document, that embedded in main document. So you should switch between main DOM and iframe DOM each time you need to handle appropriate element
Got it. Thank you a lot!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.