Shane
Shane

Reputation: 4983

Best way to locate this element in selenium?

For example, here's part of the source:

<div id = "eg_1_2_3_0399483" style = "visibility: visible; display: block;">
    <iframe id = "default_23342522" src="http://example.com/random_string_skdfjgklsjklf" style = "height: 600px;">
...

<div id = "eg_238_2348927" style = "visibility: hidden; display: none;">
    <iframe ...

You see, there's multiple iframe in the source, what I really want to locate is <iframe id = "default_23342522" src="http://example.com/random_string_skdfjgklsjklf" style = "height: 600px;"> but as the id and src keep changing each time you load the page, so basically I would first locate <div id = "eg_1_2_3_0399483" style = "visibility: visible; display: block;"> then go for its child node, the problem is, how do you do that? Well I know the way to locate the first <div> element is like this:

element = browser.find_elements_by_xpath("//div[@style='visibility: visible; display: block;']")

And then?

Or maybe some better ideas on how to locate the iframe element above?

Upvotes: 1

Views: 966

Answers (1)

Thanasis Petsas
Thanasis Petsas

Reputation: 4448

Try this:

element = browser.find_elements_by_xpath("//div[@style='visibility: visible; display: block;']/iframe[@style='height: 600px;']")

If you want only the first iframe in the specified div each time (as shown in your answer), do then

iframe=element[0]

If you want to extract what is inside the iframe then you can do this:

iframe_content = iframe.text

An alternative way to locate the first iframe of the specified div is by using a similar function that returns one item instead of a list:

element = browser.find_element_by_xpath("//div[@style='visibility: visible; display: block;']/iframe[1]")

Above we used find_element_by_xpath instead of find_elements_by_xpath to just locate the first iframe of the specified div. Take in mind that I didn't specified the iframe by its style (e.g. height: 600px). But this can be done here too in a similar way as I explained above using find_elements_by_xpath.

Upvotes: 1

Related Questions