Home > Mobile >  Selenium Click button whitout id
Selenium Click button whitout id

Time:12-30

i have to click the input type="button" element of the first li, but i can not refer to the id of the li, since it changes every time i i open the website, this is what i tried

driver.find_elements_by_xpath('//input[data-componentname="gender"]').get(0).click()

and it gives me this error:

AttributeError: 'list' object has no attribute 'get'

if i remove the get part, this is the error:

AttributeError: 'list' object has no attribute 'click'

This is the code, like i said, i have to click the first input without referring to the id

<ul data-componentname="gender">
    
      <li id="78ece221-1b64-4124-8483-80168f21805f" >
        <input type="button">
        <span>Uomo</span>
      </li>
    
      <li id="2678a655-b610-41e0-8e7f-bad58fbcb1b3" >
        <input type="button">
        <span>Donna</span>
      </li>
    
  </ul>

CodePudding user response:

To click on the element Uomo you need to induce Ummo

CodePudding user response:

find_elements method return a list of web elements.
The first member of the list can be received by simple indexation i.e. list_object[0]
Also, since you want to get the first element matching the //input[data-componentname="gender"] locator you can simply use find_element method.
So, instead of

driver.find_elements_by_xpath('//input[data-componentname="gender"]').get(0).click()

You can use

driver.find_element_by_xpath('//input[data-componentname="gender"]').click()

Or

driver.find_elements_by_xpath('//input[data-componentname="gender"]')[0].click()

UPD
well, you tried to use a wrong locator.
This should work:

driver.find_element_by_xpath("//ul[@data-componentname='gender' ]//span[text()='Uomo']/../input").click()

You can also click the element containing the "Uomo" text itself as well

driver.find_element_by_xpath("//ul[@data-componentname='gender' ]//span[text()='Uomo']").click()

CodePudding user response:

You can include the first li if you only want that. For example:

driver.find_element_by_xpath('//input[data-componentname="gender"]/li[1]')

otherwise if you want the list then you can do

driver.find_elements_by_css_selector('input[data-componentname="gender"] > li')

and do the .get() according to which button you want to click

  • Related