Home > front end >  Selenium find(By.XPATH) cannot locate element using array of xpaths
Selenium find(By.XPATH) cannot locate element using array of xpaths

Time:09-04

I'm having this weird issue where Selenium cannot discern properly if it has found an xpath if it is looping through an array of xpaths. For example:

input_type = ['numeric', 'text', 'multipleChoice']

for item in input_type:
  print(f"Current input: {item}")
  form_number = driver.find_elements(By.XPATH,'//label[starts-with(@for, "urn:li:fs_easyApplyFormElement")][contains(@for, '  item  ')]')
  if form_number:
    print(item)

As you can see, I am trying to loop through an array of possible xpath input types. However, it seems that if one element of the array is found, then all possible form_numbers are considered found. So for example if "numeric" is located, then "text" and "multipleChoice" will also print(item). If none are found, none are printed.

You can easily replicate this issue if you replace the xpath with one which you have access to.

I need this loop to print(item) only if the xpath specified by the specific item in the array is found, so for "numeric" it would print(item), however not for "text or "multipleChoice". I've played around with this in many contexts and the functionality still remains the same.

Thanks for your help with this confusing issue!

CodePudding user response:

@Zane Baylon, I tried replicating this, but I found it is not finding the Xpath even if it is there as the attribue value is not double-quoted. So the output is similar to the below:

Current input: numeric
Current input: text
Current input: multipleChoice

But if I slightly change the XPath as below:

input_type = ['numeric', 'text', 'multipleChoice']
for item in input_type:
  print(f"Current input: {item}")
  form_number = driver.find_elements(By.XPATH,'//input[@name="'  item  '"]')
  if form_number:
    print(item)

Then the output is:

Current input: numeric
numeric
Current input: text
Current input: multipleChoice

which is what I think you are expecting.

XPath that you have created is:

//label[starts-with(@for, "urn:li:fs_easyApplyFormElement")][contains(@for, numeric)]

and what I modified has a double quote to surround the attribute value:

//label[starts-with(@for, "urn:li:fs_easyApplyFormElement")][contains(@for, "numeric")]
  • Related