用绝对URL替换html中的相对URL

时间:2014-09-24 03:21:30

标签: regex node.js web-scraping

我正在抓一个外部网页保存到文件中,但有时这个文件包含我无法查看的相对网址,因为找不到这些文件。我希望用绝对网址替换。我对某些模块或函数感兴趣,将html字符串中的所有相对URL替换为绝对值。有什么想法吗?

var request = require('request');
var WEBSITE = 'http://somewebsite.com/';
request.get(WEBSITE, function(error, response, body){
    body = replace_all_relative_by_absolute(body);
    console.log(body);
});

2 个答案:

答案 0 :(得分:0)

您可以迭代链接并自行添加域名。

使用jQuery,安装时使用:

npm install -S 'jquery@>=2.1'
npm install -S 'jsdom@latest'

示例实现(几乎未经测试):

var env = require('jsdom').env;

function addDomainToLinks(domain, html, callback) {
  env(html, function (err, window) {
    var $ = require('jquery')(window);
    $.each($('a'), function(i, v) {
      var href = $(v).attr('href');
      // Match links starting with /, but not //
      // You probably want to do handle './', and do the same for images, etc.
      if (href.match(/^\/[^\/]/)) {
        $(v).attr('href', domain + href);
      }
    });
    callback($('html')[0].outerHTML);
  });
}

用法:

addDomainToLinks('http://example.com', html, function(html) {
  console.log(html);
});

答案 1 :(得分:0)

导入此

    from urlparse import urljoin

然后

    urljoin(base_url, file_url)
相关问题