2

I'm using selenium and phantomjs and I would like to learn how to click a checkbox properly. For exemple in this page: https://www.udacity.com/courses/android

I would like to check "Free Courses", so I tried this:

from selenium import webdriver
from selenium.webdriver.common.by import By


def __init__(self):
        self.driver = webdriver.PhantomJS(executable_path='/usr/local/bin/phantomjs')

    def parse(self, response):
        self.driver.get(response.url)
        element = self.driver.find_element(By.XPATH, '//div[@class="checkbox"]/label[contains(.,"Free Courses")]')
        self.driver.execute_script("arguments[0].click();", element)

The problem is that it doesn't seems to be clicking anything: making a screenshot with self.driver.save_screenshot('screenshot.png') it gives all the results, not filtered. Is it something I'm doing wrong?

Artjom B.
  • 61,146
  • 24
  • 125
  • 222
Lara M.
  • 855
  • 2
  • 10
  • 23
  • Why not to use `self.driver.find_element(By.XPATH, '//div[@class="checkbox"]/label[contains(.,"Free Courses")]').click()` ? Also you should use `input` element instead of `label` – Andersson Jul 28 '16 at 12:57
  • The .click() function seems to be not supported in PhantomJS, see: http://stackoverflow.com/questions/15739263/phantomjs-click-an-element It's true I was using label erroneously. – Lara M. Jul 28 '16 at 13:15

1 Answers1

0

Your xpath locates to label element while you want to click on checkbox element, As I'm seeing in your provided website, there is no need to create xpath to select Free Course checkbox, you can simply find this checkbox using By.NAME as below :-

from selenium import webdriver
from selenium.webdriver.common.by import By


def __init__(self):
        self.driver = webdriver.PhantomJS(executable_path='/usr/local/bin/phantomjs')

   def parse(self, response):
      self.driver.get(response.url)
      element = self.driver.find_element(By.NAME, 'Free Course')
      element.click()

Note :- Selenium provides click() function to perform click on an element, So there is no need to use execute_script to perform click by javascript if you could simply do this by using click() function.

Hope it helps...:)

Saurabh Gaur
  • 23,507
  • 10
  • 54
  • 73
  • Thanks, it works! I used the execute_script 'cause I read that in PhantomJS the click() function doesn't work. Thank you – Lara M. Jul 28 '16 at 13:09
  • 1
    @LaraM. You welcome, Glad to help you..due some reasone like designing or other issues `click()` does not work then you can use `execute_script` otherwise `click()` works perfectly....:) – Saurabh Gaur Jul 28 '16 at 13:14