I'm trying to select an item from a bootstrap dropdown with selenium. I can click the dropdown itself and get the options shown, but I can't click any option.
I tried different things but I'm getting:
TypeError: 'str' object is not callable
This is the line that I need to fix:
option = driver.find_element(By.XPATH("//li[text()='Element'"))
option.click()
I also tried using this code with the same error:
options = driver.find_elements(By.XPATH("//ul[contains(@class,'a-list')]/a"))
for option in options:
optionText = option.text()
if optionText == ('Element'):
option.click()
break
I also tried using these codes with different xpath in case that was the mistake, but keep getting the same error.
I'd appreciate any help. Thanks in advance!
CodePudding user response:
You can open the CSS option on https://www.jquery-az.com/bootstrap4/demo.php?ex=79.0_1
page with simple 2 clicks:
- Click the drop down button.
- Click the desired option.
Of cause you need to wait for these elements clickability before performing the clicks, but this can be achieved withWebDriverWait
expected conditions.
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(service=webdriver_service, options=options)
url = "https://www.jquery-az.com/bootstrap4/demo.php?ex=79.0_1"
driver.get(url)
wait = WebDriverWait(driver, 20)
wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "button"))).click()
wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "a[href*='css']"))).click()
CodePudding user response:
You have a few different typos with your code:
find_element()
should take two arguments (not one), the first is the selector type such asBy.XPATH
, which translates to"xpath"
. The second argument should be a selector of that type.By.XPATH
is a string, not a method (you used it like a mathod).- Your first selector was missing a closing bracket,
]
.
Try this, which fixes your issues:
option = driver.find_element(By.XPATH, "//li[text()='Element']")
option.click()