简体   繁体   English

Selenium find(By.XPATH) 无法使用 xpaths 数组定位元素

[英]Selenium find(By.XPATH) cannot locate element using array of xpaths

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.我遇到了这个奇怪的问题,如果 Selenium 找到了 xpath 如果它正在循环通过一组 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.如您所见,我正在尝试遍历一组可能的 xpath 输入类型。 However, it seems that if one element of the array is found, then all possible form_numbers are considered found.但是,似乎如果找到数组的一个元素,则认为所有可能的 form_numbers 都已找到。 So for example if "numeric" is located, then "text" and "multipleChoice" will also print(item).因此,例如,如果“numeric”被定位,那么“text”和“multipleChoice”也将打印(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.如果您将 xpath 替换为您可以访问的一个,则可以轻松复制此问题。

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.仅当找到数组中特定项目指定的 xpath 时,我才需要此循环来打印(项目),因此对于“数字”,它将打印(项目),但不适用于“文本”或“多重选择”。我玩过在许多情况下都与此相关,并且功能仍然保持不变。

Thanks for your help with this confusing issue!感谢您对这个令人困惑的问题的帮助!

@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. @Zane Baylon,我尝试复制它,但我发现它没有找到 Xpath,即使它存在,因为属性值没有双引号。 So the output is similar to the below:所以 output 类似如下:

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

But if I slightly change the XPath as below:但如果我稍微改变 XPath 如下:

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:那么output就是:

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

which is what I think you are expecting.这就是我认为你所期待的。

XPath that you have created is:您创建的 XPath 是:

//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")]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM