2015-04-07 120 views
1

我希望能夠以文本發送到該文本框元素非靜態ID元素:如何找到使用硒的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_之後的數字是動態生成的)。

我也試過,但我得到一個錯誤說「未知錯誤:無法對焦元素」:

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

回答

0

使用試試這個XPath的開始,與

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

您得到錯誤的原因可能是因爲您的選擇器最終會得到div而不是您需要的textBox

1

試試下面的CSS

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

你想要的第一個文本我以爲區域框placeholder="Compose your message" 如果是這樣,您還可以使用以下cssSelector

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

部分搜索與ID也是可能的。假設div的ID的集裝箱部分是獨一無二的,靜態的,你可以做以下

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

在另一方面,如果你想在第二textarea的只是簡單地改變子指標

[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"); 
+0

謝謝你,我從你的解釋中學到了很多東西。但它說「元素不可見」我嘗試使用下面的海報建議的方法,它爲我工作。 –

+0

@MJJ_PDX哪一個返回*元素不可見*? – Saifur