Rico Strydom
Rico Strydom

Reputation: 549

Selenium : xpath following-sibling where siblings have more children

I hope I describe my problem/question in a comprehensible way.

I have and html that looks like this:

<div class="class-div">
	<label class="class-label">
		<span class="class-span">AAAA</span>
	</label>
	<div class="class-div-a">
		<textarea class="class-textarea">
		</textarea>
	</div>
</div>
<div class="class-div">
	<label class="class-label">
		<span class="class-span">BBBB</span>
	</label>
	<div class="class-div-a">
		<textarea class="class-textarea">
		</textarea>
	</div>
</div>

I want the Xpath for the TextArea where the value of the Label is AAAA to populate it with a value in Selenium.

So somelike like this...

wait.Until(ExpectedConditions.ElementIsVisible(
    By.XPath("//div[@class='class-div']/label[@class='class-label'][span[@class='class-span' and text()='AAAA']]/following-sibling::div[@class='class-div-a']/textarea[@class='class-textarea']"))).SendKeys(valueTextArea);

Upvotes: 1

Views: 2247

Answers (2)

mrfreester
mrfreester

Reputation: 1991

Let me quickly rephrase the question to make sure I understand, you need an xpath to find the textbox associated with the label where the text is AAAA.

You'll have to go back up the tree in this case, here are a couple of ways I might do that, although your xpath looks correct:

Using ancestor to be clear about which element you're moving up to (better IMO)

By.XPath("//label/span[text()='AAAA']/ancestor::div[@class='class-div']//textarea");

Or just moving back up the tree with ..

By.XPath("//label/span[text()='AAAA']/../../..//textarea");

If your xpath exists, use asikojevics answer. The C# method is ExpectedConditions.ElementExists(By)

****UPDATE****

Based on your comment of a trailing space after the text value, here is another xpath that should find the textarea in that case, using contains instead of text()=.

By.XPath("//label/span[contains(text(),'AAAA')]/ancestor::div[@class='class-div']//textarea");

Upvotes: 0

acikojevic
acikojevic

Reputation: 945

Problem could be in this waiter condition, ExpectedConditions.ElementIsVisible

The thing is that your <textarea> is not 'visible' in selenium context, visibility means that element is present in DOM (which is true) and it's size is greater then 0px which could be false for your <textarea> element. In java you would use ExpectedConditions.presenceOfElement() instead of ExpectedConditions.visibilityOfElement(), not sure how it goes in C# but you get the picture.

Try and see if it solves your problem.

Upvotes: 2

Related Questions