2

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()
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
luis morales
  • 31
  • 1
  • 5

3 Answers3

3

You actually can use document.getElementsByClassName() through execute_script() call:

driver.execute_script("document.getElementsByClassName('accordion-toggle')[0].click();")

But I would not go down to executing javascript for such a simple task. Easier to locate the element using find_element_by_class_name():

accordion = driver.find_element_by_class_name('accordion-toggle')
accordion.click()
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
0

You are looking for find_element(s)_by_css_selector - reference 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.
Community
  • 1
  • 1
StuartLC
  • 104,537
  • 17
  • 209
  • 285
0

In addition to @alecxe response, I would also suggest using the function find_elements_by_class_name instead of find_element_by_class_name in case there are multiple elements with the same class name.

accordion = driver.find_elements_by_class_name('accordion-toggle')[1] # Selects second element
accordion.click()

Using find_element_by_class_name will return only the first element with that class name.

Guillermo Garcia
  • 528
  • 4
  • 11