使用组合 xpath 定位元素并单击它

Using composed xpath to locate an element and click on it

我正在尝试使用 XPATH 检索元素列表,我想从此列表中检索基于类名的子元素并单击它。

var rowList = XPATH1 + className;
var titleList = className + innerHTMLofChildElement;

 for(var i = 0; i < titleList.length; i++) {
                if(titleList[i][0] === title) {
                    browser.click(titleList[i][0]);  //I don't know what to do inside the click function
            }
        }

我不知道 node.js,但在 Java 你应该通过以下方式实现你的目标:

titleList[i].findElementBy(By.className("classToFind"))

假设 titleList[i] 是您要从中获取子元素的列表中的一个元素

我的实现可能与您正在尝试做的类似,但是由于使用 CSS 选择器而不是 XPath,我的实现可能更复杂。我确定这没有优化,很可能会得到改进。

这使用 WebdriverIO 的 elementIdText()elementIdClick() 方法来处理 Web JSON 元素的 "Text Values",然后在匹配您想要的元素后单击预期的元素正在寻找。

http://webdriver.io/api/protocol/elementIdText.html http://webdriver.io/api/protocol/elementIdClick.html

第 1 步 - 找到您想要使用的所有潜在元素:

// Elements Query to return Elements matching Selector (titles) as JSON Web Elements. 
// Also `browser.elements('<selector>')`
titles = browser.$$('<XPath or CSS selector>') 

第 2 步 - 循环浏览元素,去除 InnerHTML 或文本值并将其推入单独的数组:

// Create an Array of Titles
var titlesTextArray = [];
titles.forEach(function(elem) {
    // Push all found element's Text values (titles) to the titlesTextArray 
    titlesTextArray.push(browser.elementIdText(elem.value.ELEMENT))
  })

第 3 步 - 循环浏览标题文本值数组以找到您要查找的内容。使用 elementIdClick() 函数点击你想要的值:

//Loop through the titleTexts array looking for matching text to the desired title.
for (var i = 0; i < titleTextsArray.length; i++) {
  if (titleTextsArray[i].value === title) {
    // Found a match - Click the corresponding element that  
    // it belongs to that was found above in the Titles
    browser.elementIdClick(titles[i].value.ELEMENT)
  }
}

我将所有这些打包到一个函数中,在该函数中我提供了我想要搜索的预期文本(在您的情况下是特定的 title)。希望这对您有所帮助!