Selenium Python document.getElementsByClassName()

I’m using Selenium with Python3 to automate entering data into a website. I have tried looking everywhere for how to deal with selecting an element by class if there is more than one but I can’t figure out how to select the accordion-toggle[1]. Nothing happens on selenium but it works fine on any browser. Also, is there any way to just use the regular javascript or jquery commands?:

accordion=find_element_by_class("accordion-toggle"[1])
accordion.click()
#otheraccordion=find_element_by_css_selector("#AdvancedAddress > div.accordion-heading.in > div.accordion-toggle > span.accordionExpandCollapse")
#otheraccordion.click()
StreetNameField=driver.find_element_by_id("Advanced_FindMyParcel_PropertyStreetName")
StreetNameField.send_keys("Sherman")
ZipField=driver.find_element_by_id("Advanced_FindMyParcel_PropertyZip")
ZipField.send_keys("90201")
ZipButton=driver.find_element_by_id("btnSearchFindMyParcels")
ZipButton.click()

Answer

You are looking for find_element(s)_by_css_selectorreference here – use the css prefix ‘.classname` to indicate the class.

e.g. to find

<div class='theClass'>

driver.find_elements_by_css_selector('.theClass')

You can also use the By syntax:

driver.find_elements(By.CSS_SELECTOR, '.theClass')

Edit
It seems the problem may be more to Clicking the element, rather than finding it.

  • Ensure the element is visible
  • For Chrome, you may need to mimic hovering the mouse over the element before clicking this – see Actions / ActionChains MoveToElement to hover over the element.
  • For IE, you may need to ensure the browser / frame gets the focus, prior to the element Click – you may need to apply a hack like one of these.