如何使用 Selenium Webdriver C# 查找具有非静态 ID 的元素

How to find element with non-static ID using Selenium Webdriver C#

我希望能够将文本发送到此文本框元素:

<form class="compose okform initialized">

    <div class="border"></div>
    <div id="message_9028519832635440005Container" class="inputcontainer textarea empty">
        <textarea class="clone" placeholder="Compose your message" aria-hidden="true" style="height: 21px; width: 417px; line-height: 18px; text-decoration: none; letter-spacing: 0px;" tabindex="-1"></textarea>
        <textarea id="message_9028519832635440005" placeholder="Compose your message" style="height: 39px;"></textarea>

        <span class="okform-feedback message empty" style="height: 0"></span>
        <div class="icon okicon"></div>
    </div>
    <button class="flatbutton" type="submit"></button>
    <div class="draft_message"></div>
    <label class="checkbox" for="enter_to_send_9028519832635440005"></label>

</form>

我无法通过搜索部分 ID(message_ 之后的数字是动态生成的)来定位元素。

我也试过了,但我收到一条错误消息 "unknown error: cannot focus element":

var textBox = DriverActions.driver.FindElements(By.ClassName("inputcontainer"));
textBox[0].SendKeys("Why hello");

试试下面的方法css

.inputcontainer.textarea.empty>textarea:nth-child(1)

我假设您想要第一个带有 placeholder="Compose your message" 的文本框 如果是这样,您还可以使用以下 cssSelector

[placeholder='Compose your message'][class='clone']

也可以使用 id 进行部分搜索。假设 Container 部分 div 的 id 是唯一且静态的,您可以执行以下操作

[id$='Container']>textarea:nth-child(1)

另一方面,如果您想要第二个文本区域,只需更改子索引即可

[id$='Container']>textarea:nth-child(2)

并且,这是实现

By byCss = By.CssSelector("[id$='Container']>textarea:nth-child(1)");
IWebElement textBox = driver.FindElement(byCss);
textBox.SendKeys("Why hello");

使用 starts-with

试试这个 XPath
var textBox= DriverActions.driver.FindElement(By.XPath(".//textarea[starts-with(@id,'message_')]"));
textBox.SendKeys("Why hello");

您收到错误的原因可能是因为您的选择器最终会得到一个 div 而不是您需要的 textBox