Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clicking label element that unfortunately contains a link

I'm running into an issue where I'm attempting to click on a checkbox. The app is written in AngularJS.

The checkbox can not be clicked, as technically the element is not visible. Using 'visible: false' does not help to get this box checked. I have also tried to use element.set(true)

The checkbox is within a label element that happens to also contain hyperlinks. Since Capybara/Selenium clicks on the middle of an element by default, I end up opening the hyperlink instead of marking the checkbox. Clicking within anywhere in the label (outside of the hyperlinks) checks the box successfully.

How can I achieve this?

like image 254
Phil Avatar asked Sep 27 '22 16:09

Phil


2 Answers

I would recommend using JavascriptExecutor to click element. In case element is technically not visible Webdriver will not allow you to click it using API, as it tries to simulate real user actions. Nevertheless you have the option to execute JS directly, which doesn't really care.

This answer will help you with the code part: https://stackoverflow.com/a/19934852/2998104

You would need to change ending slightly to:

JavascriptExecutor js = (JavascriptExecutor) driver;
WebElement element = driver.findElement(By.xpath("exact_locator_of_checkbox"));
js.executeScript("arguments[0].click()",element);

Of course no need to use only xpath, but anything that help you point to the checkbox directly.

like image 153
Kudin Avatar answered Oct 10 '22 10:10

Kudin


Took me a little while but I figured out that I can avoid the Capybara API and use WebDriver's ActionBuilder.

def agree
  source = find('label.terms-label').native
  actionbuilder = page.driver.browser.action
  actionbuilder.move_to(source, 0, 0).click.perform
end

By default, the Capybara API (as well as other native Selenium methods) will click in the center of the element. This will avoid that and will find the element and click it at (0, 0) coordinates.

like image 20
Phil Avatar answered Oct 10 '22 10:10

Phil