Home > Mobile >  Selecting a specific element with Selenium - Python
Selecting a specific element with Selenium - Python

Time:09-14

I'm trying to click this button shown after choosing an option from a drop-down menu. This is the button I'm trying to click. enter image description here

The link to the website: enter image description here

I've tried using XPATH, and through visible text; nothing seems to work. My code as of now:

from selenium import webdriver
from selenium.webdriver.common.by import By
import time
from selenium.webdriver.support.ui import Select

PATH = "C:\Program Files (x86)\chromedriver.exe"
driver = webdriver.Chrome(PATH)

driver.get("https://excise.wb.gov.in/CHMS/Public/Page/CHMS_Public_Hospital_Bed_Availability.aspx")
drop_dist = \
driver.find_element(By.XPATH, "/html/body/form/div[3]/main/div[2]/div/div[2]/div/div[1]/div[2]/div/select")
select_dist = Select(drop_dist)
select_dist.select_by_value("005")
l = driver.find_element(By.XPATH, "/html/body/form/div[3]/main/div[2]/div/div[2]/div/div[4]/div/div/table/tbody/tr[1]/td/div/div[2]/div[2]/div[1]/a").click()
time.sleep(30)

Any help is much appreciated!

CodePudding user response:

The locator seems fragile, use following locator and webdriverwait() to handle sync issue.

driver.get("https://excise.wb.gov.in/CHMS/Public/Page/CHMS_Public_Hospital_Bed_Availability.aspx")
wait=WebDriverWait(driver, 20)
select_dist =Select(wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, "#ctl00_ContentPlaceHolder1_ddl_District"))))
select_dist.select_by_value("005")
wait.until(EC.element_to_be_clickable((By.XPATH, "(//a[@class='btn btn-link' and contains(., 'View Detail Break up')])[1]"))).click() //this will click the first one only.

You have to add following imports.

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

CodePudding user response:

Try this:

button = driver.find_elements(By.CSS, 'a[role="button"][aria-expanded="false"]')[0]
button.click()

You can change the index in order to click on other elements

  • Related