1

我对 phantomjs 很陌生。我一直在搞乱以下内容太久了。我知道我错过了一些非常简单的东西。我有以下 sitemap.xml:

<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd">
  <url>
    <loc>/</loc>
    <changefreq>always</changefreq>
    <priority>1.0</priority>
  </url>
  <url>
    <loc>/vehicles</loc>
    <lastmod>2013-01-07</lastmod>
  </url>
</urlset>

现在我要做的就是使用 phantomjs 从 xml 文档中获取 url 值。我有以下。

page.open("sitemap.xml", function(status) {
    if(status !== "success") {
        console.log("Unable to open sitemap.");
    } else {
        // Stuck here
        console.log(page.content);
    }
});

xml文件的内容正确打印到屏幕上,但是我现在如何使用文档来播放xml?我只需要能够获取每个 url 节点的第一个子节点。我尝试将 xml 文档解析为 DOMParser,但这似乎不对。您的帮助将不胜感激。

另外,您如何调试 phatomjs 以便我可以看到该对象的全部荣耀?例如,如果我在 Dev Tools 中 console.log 一个对象,我可以展开它并查看键值对。我猜终端不提供这种奢侈品?

4

4 回答 4

5

PhantomJS 允许您从页面上下文中调用 javascript。使用普通的旧 javascript 查看我的解决方案。

假设站点地图看起来像这样

<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd">
<url>
<loc>http://example.com/</loc>
<lastmod>2014-07-07T14:09:27+00:00</lastmod>
<changefreq>always</changefreq>
</url>

我可以使用下面的代码在上面的站点地图中获取 url。

var page = require('webpage').create();
page.open('http://xxxx/static/sitemap/sitemap.xml', function() {
        var content = page.content;
        parser = new DOMParser();
        xmlDoc = parser.parseFromString(content,'text/xml');
        var loc = xmlDoc.getElementsByTagName('loc');
        console.log(loc.length);
        for(var i=0; i < loc.length; i++)
        {
          var url=loc[i].textContent;

        }

        phantom.exit();
});
于 2014-07-09T05:40:24.400 回答
3

使用libxmljs解析您的 xml 字符串并获取您想要的数据!

于 2013-01-07T17:23:10.560 回答
0

另一个想法,您可以将 jQuery 注入页面并像这样解析 xml:

page.open("sitemap.xml", function(status) {
    if(status !== "success") {
        console.log("Unable to open sitemap.");
    } else {
        // Stuck here
        console.log(page.content);
        page.injectJs('j-query.js');//path to jquery
        var output = page.evaluate(function(){
                            return $('url *:first-child');           
                       });
    }
});
于 2013-01-08T21:10:22.167 回答
0

有人创建了一个使用 casperjs 测试 XML 站点地图的测试套件,也许您可​​以根据您的特定需求采用代码。

来自作者:

该脚本将尝试爬取指定的站点地图,以检查子页面是否存在损坏的 url、图像、css 和 Javascript。错误将被记录到指定的日志文件中。

用法:

casperjs sitemap_xml_testing.js --sitemap=<URL TO SITEMAP> --logfile=<LOG FILE NAME>

在 Bitbucket 上进行 gmazin 自动化站点地图测试

于 2014-10-10T10:43:30.583 回答