简体   繁体   English

如何通过使用C#和Selenium使用InnerHTML进行搜索来查找元素

[英]How to find an element by searching with InnerHTML using C# and Selenium

I want to get a particular element id by searching for a matching innerHTML string. 我想通过搜索匹配的innerHTML字符串来获取特定的元素id。 For example I want to find the element id that has the innerHTML "Start of Car". 例如,我想找到具有innerHTML“Start of Car”的元素id。

在此输入图像描述

public static bool SelectSomething(IWebDriver driver, string searchName)
{
    var js = driver as IJavaScriptExecutor;
    if (js == null) return false;
    var element = (string) js.ExecuteScript("...script to get the ids...");
    var x = driver.FindElement(By.Id(element));
    x.Click();
    return true;
}

I know it is possible to loop through and find all of the innerHTML using JavaScript but how do you return the id once you find innerHTML that matches the 'searchName' string? 我知道可以使用JavaScript循环查找所有innerHTML,但是一旦找到匹配'searchName'字符串的innerHTML,你如何返回id?

Using jQuery it is simple, just use :contains - https://api.jquery.com/contains-selector/ 使用jQuery很简单,只需使用:contains - https://api.jquery.com/contains-selector/

http://jsfiddle.net/jayblanchard/5UvFE/ http://jsfiddle.net/jayblanchard/5UvFE/

var found = $("td:contains('Start of Car')").attr('id');

This allows you to return the ID of the element in question. 这允许您返回相关元素的ID。

Alternatively here is a way to do it with just JavaScript - 另外,这是一种只使用JavaScript的方法 -

function textID(node, text) {
    if (node.nodeValue == text) {
        return node.parentNode;
    }

    for (var i = 0; i < node.childNodes.length; i++) {
        var returnValue = textID(node.childNodes[i], text);
        if (returnValue != null) {
            return returnValue;
        }
    }

    return null;
}

http://jsfiddle.net/jayblanchard/5UvFE/1/ http://jsfiddle.net/jayblanchard/5UvFE/1/

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

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