Home > Net >  can't select a checkbox in webdriver.Chrome python
can't select a checkbox in webdriver.Chrome python

Time:12-20

I'm trying to create a script to show only pikachus on donate view

CodePudding user response:

There are several problems with your code:

  1. There is no element with ID = 'search_pokemon'
  2. There is no frame there to switch into it.
  3. You need to use WebDriverWait expected_conditions to wait for elements to be clickable.
  4. And generally you need to learn how to create correct locators.
    The following code works:
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()

The result is:

enter image description here

UPD

  1. This time I saw the donation dialog so I added the mechanism to close it.
  2. I still can't see there element with ID = 'search_pokemon' as you mentioned.
  3. As about the XPath to find the relevant checkbox - when pokemon name is inserted you can see in the dev tools that there are a lot of checkboxes there but all of them are invisibly while only one in our case is visible. The invisible elements are all have attribute style="display: none;" while the enabled element does not have style attribute. This is why [not(@style)] is coming there. So, I'm looking for parent element //div[@class='filter_checkbox'] who is also have no style attribute. In XPath words //div[@class='filter_checkbox'][not(@style)] then I'm just looking for it label child to click it. This can also be done with CSS Selectors as well.

The list of invisible elements with the enabled one:

enter image description here

  • Related