How to find out xpath for iframes.Below is the pic

2019-08-23 06:24发布

问题:

I need to find out text " brands related to your search" in below image

How can i write the xpath.The text is present in an iframe which has no id or class or no unique identifier.I was thinking to find it using span data component id but it did not work.

By.xpath("//span[@data-component-id='36']/iframe

Please help

https://i.stack.imgur.com/7EW5n.png

回答1:

You cannot traverse the elements on an <iframe>, it lives in a different context. You need to activate or switch to the context of the iframe, eg. using JavaScript to interact with an iframe and the document inside of it.

//Note: Assigning document.domain is forbidden for sandboxed iframes, i.e. on stacksnippets
//document.domain = "https://stacksnippets.net";

var ifrm = document.getElementById("myFrame");
// reference to iframe's window
//var win = ifrm.contentWindow;
// reference to document in iframe
var doc = ifrm.contentDocument ? ifrm.contentDocument : ifrm.contentWindow.document;
// reference an element via css selector in iframe
//var form = doc.getElementById('body > div > div.message');
// reference an element via xpat in iframe
var xpathResult = doc.evaluate("/html/body/div/div[1]", doc, null, XPathResult.ANY_TYPE, null);
<iframe id="myFrame" src="https://stacksnippets.net" style="height:380px;width:100%"></iframe>

However, as you can see when you run the snipped, cross-document interactions are only possible if the documents have the same origin. There are other, more involved methods like the postMessage method that provide the means of interacting cross-domain.



标签: xpath iframe