Lara M. Lara M. - 4 months ago 48
Python Question

Phantomjs click on checkbox

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?

Answer

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...:)