如何在没有 id 的 iframe 中获取 div class 中的文本?

How to get a text in a div class inside an iframe with no id?

我正在尝试编写一个从以下 html 页面提取网站的 tampermonkey 脚本:

<html>
    <head></head>
    <body>
        <iframe src="http://some-url.com/ll" title="test" name="ws_block" frameborder="0" scrolling="no" style="border:0px; width:100%; height: 320px;">
            <html>
                <head>
                        <!-- A particular character set can be specified by assigning "charset" -->
                    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
                    <title>Title</title>
                    <link rel="stylesheet" href="/en/Custom/blockStyle.css" type="text/css">
                </head>
                <body>
                    <div class="wrapper">           
                        <div id="logo"><img src="/banner.gif" alt="[ORG]" border="0"></div>
                        <div class="block-body">
                            <div class="textLine">
                                <div class="ws-label label" data-strid="url"><script> ws.print("url"); </script>Address:</div>
                                <div class="text">https://www.my_website.com/</div>
                            </div>
                            <div class="textLine">
                                <div class="ws-label label" data-strid="category"><script> ws.print("category"); </script>Category:</div>
                                <div class="text">My-Website</div>
                            </div>
                        </div>
                    </div>  
                </body>
            </html>
        </iframe>
    </body>
</html>

我正在尝试提取我的网站 link:
https://www.my_website.com/

window 对象有一个 frames 数组,其中包含页面中包含的所有 iframe,因此您可以迭代它并尝试获取您的内容。

如果您只有 iframe,那么 window.frames[0].getElementsByClassName(classname) 就可以了。

请在 MDN

查看其文档

出于安全原因,您无法通过 javascript 访问其他源(域)iframe!

你应该使用像 php!

这样的服务器端语言来完成

如果域和 iframe src 同源,您可以使用 :

window.frames[0].getElementsByClassName(classname)

有许多不同的方法可以在 DOM 中查找元素,而无需使用其 ID。

您需要找到该元素的其他一些识别特征并加以利用。

例如:

document.querySelector("iframe");

…将return第一个文档中的iframe。


之后,您将使用与通过 id 获取 iframe 时完全相同的方法。