Search code examples
pythoncriteriapywinautoambiguous

How to getting around pywinauto's ElementAmbiguousError: There are 2 elements that match the criteria error


I am trying to automate running Rufus using python and pywinauto.
So far I have been able to run the executable and modify the controls on Rufus' main screen.
After the code I have written clicks the "START" button, Rufus displays a popup. This popup is warning you that the whole contents of the USB key are going to be erased. What I am unable to do is to connect to that popup and press the "OK" button there.

Here is the code I have written:

# Connect to an existing window with title matching a regular expression
def ConnectWindow(exp):
  # Look for window matching regular expression
  try:
    handles = pwa.findwindows.find_windows(found_index=0, title_re=exp)
  except pwa.findwindows.WindowNotFoundError:
    handles = None
  # Make sure something was found
  if handles:
    # Make sure only one found
    if len(handles) > 1:
      print('Matched more than one window matching regular expression: {0}'.format(exp))
      sys.exit(1)
    # Return it!
    return pwa.Application().connect(handle=handles[0]).window()
  # Nothing found
  return None

popup = ConnectWindow('^Rufus$')
popup.set_focus()
pwa.keyboard.send_keys('{RIGHT}{ENTER}')

ConnectWindow does find the window and popup is of type pywinauto.application.WindowSpecification.
However, whenever I try to do anything with popup (such as set_focus) I get the following error:

pywinauto.findwindows.ElementAmbiguousError: There are 2 elements that match the criteria {'backend': 'win32', 'process': 32992}

Does anyone know how I can fix this?


Solution

  • All this code could be written much more compact. Please don't use find_windows function directly. Read the Getting Started Guide to learn how WindowSpecification's work.

    app = pwa.Application(backend="win32").connect(found_index=0, title_re=exp, timeout=10)
    popup = app.window(found_index=0, title_re=exp)
    
    popup.type_keys('{RIGHT}{ENTER}') # it calls .set_focus() inside