JSDOM:在iframe中访问div

时间:2017-08-29 08:55:35

标签: javascript html node.js iframe jsdom

我尝试从具有以下html的网站http://www.example.com中抓取一些信息:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>My site</title>
</head>
<body>
<div id="one">
    <div>
        <iframe>
           <!DOCTYPE html>
           <html>
           <head>
             <meta charset="utf-8">
             <title>My site</title>
           </head>
           <body>
             <div id="hello">
               <a href="http://example.net/somepage"><img src="http://example.net/dokuro_chan.jpg"></a>
             </div>
           </body>
           </html>
        </iframe>
    </div>
</div>
<div id="two">
    <div>
        <iframe>
           <!DOCTYPE html>
           <html>
           <head>
             <meta charset="utf-8">
             <title>My site</title>
           </head>
           <body>
             <div id="hello">
               <a href="http://example.net/somepage2"><img src="http://example.net/dokuro_chan2.jpg"></a>
             </div>
           </body>
           </html>
        </iframe>
    </div>
</div>
</body>
</html>

然后我尝试使用jsdom:

通过nodejs刮取iframe内容
const jsdom = require("jsdom");
const { JSDOM } = jsdom;

JSDOM.fromURL("http://www.example.com",{
        resources: "usable",
        runScripts: "dangerously"
}).then(dom =>{

        const divIds=["#one","#two"]

        divIds.forEach((divId)=> {
            const selector=googleAdSelector(divId)
            const iframe=dom.window.document.querySelector(selector)
            console.log("Iframe Object", iframe)
        })
        // callback(null,dom)
})

const googleAdSelector=function(divId){
        return divId+" > div > iframe";
}

我想要实现的目标是获取iframe内的hrefsrc内容。

但由于某种原因,输出是:

  

Iframe Object null

     

Iframe Object null

您是否知道如何访问html INSIDE iframe?

1 个答案:

答案 0 :(得分:0)

你需要采用不同的方法。只需使用无头浏览器在页面加载期间手动通过网络获取数据并单独处理。

相关问题