Unable to click on a checkbox using Chrome WebDriver in Python

I've been working on a script to display only Pikachus on the Singapore Poke Map. The goal is to extract coordinates for each Pikachu and print out the list. Despite trying numerous suggestions I found, I still can't get the checkbox to be set with the latest code:

from selenium import webdriver
from selenium.webdriver.chrome.service import Service as ChromeService
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.common.by import By
import time

def find_pokemon():
    links = []
    service = ChromeService(ChromeDriverManager().install())
    driver = webdriver.Chrome(service=service)
    driver.get('https://sgpokemap.com/index.html?fbclid=IwAR2p_93Ll6K9b923VlyfaiTglgeog4uWHOsQksvzQejxo2fkOj4JN_t-MN8')
    driver.find_element(By.ID, 'filter_link').click()
    driver.find_element(By.ID, 'deselect_all_btn').click()
    driver.find_element(By.ID, 'search_pokemon').send_keys("pika")
    driver.switch_to.frame(driver.find_elements(By.ID, "filter"))
    driver.find_element(By.ID, 'checkbox_25').click()

The second part of the code works when I manually check the box after setting a breakpoint and ignoring the checkbox click() exception.

If you have any new ideas or suggestions, please let me know!

As a bonus question, how do I identify and close the donation pop-up view: https://i.stack.imgur.com/blcOM.jpg

Answer №1

Here are a few issues found in your code:

  1. The element with the ID 'search_pokemon' is missing
  2. There is no frame available to switch into it.
  3. You should utilize WebDriverWait and expected_conditions to wait for elements to be clickable.
  4. It's important to understand how to create accurate locators.
    The code snippet below demonstrates a working solution:
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

options = Options()
options.add_argument("start-maximized")

webdriver_service = Service('C:\webdrivers\chromedriver.exe')
driver = webdriver.Chrome(options=options, service=webdriver_service)
wait = WebDriverWait(driver, 30)

url = "https://sgpokemap.com/index.html?fbclid=IwAR2p_93Ll6K9b923VlyfaiTglgeog4uWHOsQksvzQejxo2fkOj4JN_t-MN8"
driver.get(url)

try:
    wait.until(EC.element_to_be_clickable((By.ID, 'close_donation_button'))).click()
except:
    pass

wait.until(EC.element_to_be_clickable((By.ID, 'filter_link'))).click()
wait.until(EC.element_to_be_clickable((By.ID, "deselect_all_btn"))).click()
wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "[name='search_pokemon']"))).send_keys("pika")
wait.until(EC.element_to_be_clickable((By.XPATH, "//div[@class='filter_checkbox'][not(@style)]//label"))).click()

Check out the screenshot of the outcome:

https://i.stack.imgur.com/1mvKJ.png

UPD

  1. I managed to close the donation dialog this time.
  2. I couldn't locate the element with ID = 'search_pokemon', as you mentioned.
  3. In terms of finding the relevant checkbox using XPath - upon inserting the pokemon name, invisible checkboxes will be visible in the dev tools. However, only one of them will be enabled. The hidden elements have the attribute style="display: none;", while the visible one does not have a style attribute. Hence, I'm looking for the parent element //div[@class='filter_checkbox'] that has no style attribute. In XPath, it would be
    //div[@class='filter_checkbox'][not(@style)]
    , after which I select the child label to click on. This can also be achieved using CSS Selectors.

List of invisible elements along with the visible one:

https://i.stack.imgur.com/NqU6v.png

Answer №2

Collaborating with @Prophet, the updated code for parsing the map and retrieving all Pikachu coordinates is as follows:

from selenium import webdriver
from selenium.webdriver.chrome.service import Service as Service
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By

from keep import saveToKeep


def find_pokemon():
    links = []
    options = Options()
    options.add_argument("--headless")
    options.add_argument("disable-infobars")
    webdriver_service = Service('C:\webdrivers\chromedriver.exe')
    driver = webdriver.Chrome(options=options, service=webdriver_service)
    wait = WebDriverWait(driver, 30)

    driver.get('https://sgpokemap.com')
    try:
        wait.until(EC.element_to_be_clickable((By.ID, 'close_donation_button'))).click()
    except:
        pass
    wait.until(EC.element_to_be_clickable((By.ID, 'filter_link'))).click()
    wait.until(EC.element_to_be_clickable((By.ID, "deselect_all_btn"))).click()
    wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "[name='search_pokemon']"))).send_keys("pika")
    wait.until(EC.element_to_be_clickable((By.XPATH, "//div[@class='filter_checkbox'][not(@style)]//label"))).click()
    
    wait.until(EC.element_to_be_clickable((By.CLASS_NAME, 'pokemon_icon_img')))
    pokeList = driver.find_elements(By.CLASS_NAME, 'pokemon_icon_img')
    for poke in pokeList:
        try:
            poke.click()
            links.append(driver.find_element(By.LINK_TEXT, "Maps").get_attribute('href'))
        except Exception:
            pass

    res = []
    for link in links:
        res.append(link.split("=")[1].replace("'", ""))

    if len(res) > 1:
        saveToKeep(res)
        print("success")
    else:
        print("unsuccessful")
        find_pokemon()


if __name__ == '__main__':
    find_pokemon()
  • The headless chrome option was utilized to improve performance.

  • 'count' variable remains commented out for potential result limitation (currently restricted to 15 results only).

  • The

    wait.until(EC.element_to_be_clickable((By.CLASS_NAME,    'pokemon_icon_img')))
    line was included due to delayed icon appearance on the page.

  • This method has been made recursive to handle potential exceptions and unsuccessful attempts.

  • The saveToKeep(res) method is used to store results in Google Keep notes after obtaining an app password for secure login.

Feel free to provide any feedback or suggestions for enhancements!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Guide on choosing a checkbox within a multiple select box using Selenium WebDriver in Java

I have the following code snippet for a multiple select box on a webpage, and I am looking to automate the selection of an option group using Selenium WebDriver. <div class="ms-drop bottom" style="display: block;"> <div class="ms-sear ...

Obtaining a particular ID from a URL using PHP WebDriver Selenium: A Comprehensive Guide

I'm trying to figure out how to extract a specific ID from a URL. (Is this even possible?) For instance: // Current URL: http://test.be/certificate/create // Saving new certificate $search11 = $this->webDriver->findElement(WebDriverBy::id(&ap ...

Shifting items in a pandas dataframe column below the nth item: A step-by-step guide

My program processes the output of an OCR scan of a table and generates a dataframe. However, sometimes the rows get merged, resulting in compressed cells that include content intended for the cell below, thus shortening the column. I need to change this c ...

Searching for specific information within a JSON file (across multiple lines)

Currently, I am working on extracting specific lines of data from a JSON file. It seems that using grep in this particular scenario might be the way to go, but I could use some guidance. Below is an example of the JSON data: [ 'vlans VLAN10 vlan-id 1 ...

Unable to interact with cookies using Python's selenium package

My current project involves using Python, Selenium, and PhantomJS to access a webpage. After getting the page with driver.get and logging in, I received a notification that cookies needed to be enabled. In an attempt to access these cookies, I implemented ...

Using Python to navigate JSON files containing multiple arrays

When attempting to extract data from a JSON file and transform it into an object type, I encountered multiple arrays of latitudes and longitudes. How can I handle this using Python? Snippet of Python code* import os from flask import Flask, render_templat ...

Clearing up confusion around identifying checkbox elements using XPath in Selenium WebDriver with Java, specifically within a

HTML code <div class="modal-footer slds-modal__footer" data-aura-rendered-by="2805:0"> <div class="rssDialogText grantAccessCheckbox packagingSetupUIRssDialogFooter" data-aura-rendered-by="2595:0" data-aura-class="packagingSetupUIRssDialogFooter" ...

Creating a mouse locator program in Python: A step-by-step guide to developing a tool similar to the Free Utility for tracking mouse cursor position

Looking to create a mouse locator program using Python? (similar to the Free Utility that locates mouse cursor position) I need help displaying the coordinates in the window as the mouse moves. import tkinter as tk import pyautogui as pag win = tk.Tk() ...

Tips for optimizing JSON parsing and database writing for faster performance

I have a task that involves parsing a 200MB json file and then writing the data into an sqlite3 database using Python. Currently, my code executes successfully but it takes about 9 minutes to complete the entire process. @transaction.atomic def create_dat ...

The variable "display" in the global scope was not located

Currently working on a troubleshooting code, I've encountered an issue. When I select "other" and try to input data into the form, upon hitting continue, an error is displayed: Exception in Tkinter callback Traceback (most recent call last): File &quo ...

Navigating through JSON data in Python with a nested for loop

While working on parsing a large JSON in Python, I encountered an issue that is preventing my code from running properly. Specifically, I am parsing the JSON step by step and trying to retrieve the value of all the WHO_REGION attributes for each attr in ...

Selenium-powered Python Web Scraping

I am attempting to gather product information from Amazon, but I keep encountering the error NoElementException: Message: unable to find element: {"method":"xpath","selector":"//li[@class='a-last']"} (Session info: chrome=102.0.5005.115) The cod ...

Should I simply open the URL or navigate to a page when creating end-to-end selenium tests?

Suppose I want to enroll in a class on the 'Courses' page. I am testing the functionality of enrolling in classes. Should I access the page by clicking on the menu bar, or should I directly enter the URL of the page? ...

Conceal the results of the Yolov8 model.predict() function by Ultralytics in the terminal

After running model.predict(), the output looks like this: 0: 480x640 1 Hole, 234.1ms Speed: 3.0ms preprocess, 234.1ms inference, 4.0ms postprocess per image at shape (1, 3, 640, 640) 0: 480x640 1 Hole, 193.6ms Speed: 3.0ms preprocess, 193.6ms inference, ...

Chrome fails to read font family correctly

I created a jsfiddle that demonstrates an interesting behavior with setting and reading the font-family using jQuery. When I set the font-family to "Arial . . ." it reads back okay, enclosed in a single set of double quotes. However, when I set the font-fa ...

Selenium encountered an error when trying to execute the 'querySelector' function on the document. The selector provided, my_selector, is not recognized as a valid selector

Whenever I run this code: document.querySelector(my_selector) using selenium, an error is thrown: Failed to execute 'querySelector' on 'Document' my_selector is not a valid selector my_selector is definitely a valid selector that func ...

Looking for assistance with parsing out four numerical values from an HTML scrape using Python

I currently have code that opens a URL and retrieves HTML data into htmlA Within htmlA, I am attempting to extract 4 specific pieces of information: A date Price 1 Price 2 A percentage The section of htmlA where these 4 pieces of information are located ...

Retrieving data from relational databases based on specific conditions in Django

I've been encountering some challenges with rendering a particular view ('myprojects') that displays the projects associated with a user from the 'uProjects' model. To address this, I created an object_list to filter 'uProject ...

How can I divide a Python pandas dataset based on the presence of a specific value in a row?

I'm working with a pandas dataset that has financial data. The first row contains details about which financial KPI is being used. I am looking to split the data into multiple data frames based on the KPI value in the first row. Unnamed: 0 Instituti ...

Is Bootstrap CSS cached by Chrome?

As I began a new project, I decided to tweak the color settings in bootstrap. During debugging in Visual Studio, everything appeared as intended. However, after publishing the site for the first time on a server, I noticed that the color change I made in ...