我对 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 一个对象,我可以展开它并查看键值对。我猜终端不提供这种奢侈?
最佳答案
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();
});
关于javascript - 使用 phantomjs 抓取站点地图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14200804/