简体   繁体   中英

given a bySelector how can i get the selector of this element's child?

This is my Html :

<a class="info-button" data-voice-actions="[&quot;info&quot;, &quot;more info&quot;]" href="waze://?button=external_poi_info" id="info-button" onclick="window.location.href = this.href; return false;">
<span class="icon"></span>
<div class="btn-text">More Info</div>
</a>

I have a by.org.openqa.selenium.By selector:

By.cssSelector("#main > div > div.footer > div > a")

and I want sometimes to relate to itself, and once I want to fetch its text as in its <div class="btn-text">More Info</div> child element.

How can I generically get the selector of the child element from the original selector I have?

(I ask generically because this case repeats few times for me)

If I understood the problem you are facing clearly then two things you can do.

First, Write a crazy selector to find it.

//a[@class='info-button']/..//div[.='More Info']

Second, Find the parent element and from there find the child element

driver.findElement(By.cssSelector("#main > div > div.footer > div > a")).findElement(By.path("//div[.='More Info']")).something

Ultimately, it depends on how your application works. The following assumes that the element you are looking for is always in immediate child of your a element, and that it always has the .btn_text class. You can just manipulate selectors like any string:

String parent_sel = "#main > div > div.footer > div > a";
String child_sel = parent_sel + " > div.btn_text";

Both strings can be passed to By.cssSelector . If my assumptions are incorrect, adapt as needed. For instance if the div can be a descendant of a without necessarily be a child of it, you could concatenate " div.btn_text" to get the child_sel .

I want to fetch its text

In case you were looking for a selector that will give you text , I'll note that there is no selector you can pass to findElement to get text . This function always returns elements (or list of elements when used in its plural form). You'll have to use getText() on the element you get. (And in case you wonder: XPath in general can select text, but not when you use it through Selenium.)

You can use the below xpath to locate the "info-button":

//div[@class='footer']//a[@class='info-button']

To retrieve the text "More Info", you can use the below xpath:

//div[@class='footer']//div[.='More Info']

Edit as per OP's comment

The css-selector to get to the div element with innerHTML/text can be this:

#main > div > div.footer > div > a > div:nth-child(1)

It locates the first child element 'div' under the concerned 'a' element.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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