对于所有情况,如何使用 cheerio 获取给定页面上图像的 URL
How to use cheerio to get the URL of an image on a given page for ALL cases
现在我有一个看起来像这样的函数:
static getPageImg(url) {
return new Promise((resolve, reject) => {
//get our html
axios.get(url)
.then(resp => {
//html
const html = resp.data;
//load into a $
const $ = cheerio.load(html);
//find ourself a img
const src = url + "/" + $("body").find("img")[0].attribs.src;
//make sure there are no extra slashes
resolve(src.replace(/([^:]\/)\/+/g, ""));
})
.catch(err => {
reject(err);
});
});
}
这将处理页面使用图像 link 的相对路径并且主机名与提供的 URL 相同的一般情况。
然而,
大多数时候 URL 方案会更复杂,例如 URL 可能是 Whosebug。com/something/asdasd 而我需要的是获得 Whosebug。com/someimage link。或者更有趣的情况是使用 CDN 并且图像来自单独的服务器。例如,如果我想 link 来自 imgur 的东西,我会给出一个 link,例如:http://imgur.com/gallery/epqDj. But the actual location of the image is at http://i.imgur.com/pK0thAm.jpg 网站的子域。更有趣的是,如果我要获取 src 属性,我将拥有:“//i.imgur.com/pK0thAm.jpg”。
现在我想一定有一种简单的方法来获取此图像,因为浏览器可以非常快速且轻松地执行 "open window in new tab" 所以我想知道是否有人知道除了编写之外的简单方法一个可以处理所有这些情况的大函数。
谢谢!
这是我的函数,它最终适用于我所有使用 URL 类型内置节点的测试用例。我只好使用解析函数。
static getPageImg(url) {
return new Promise((resolve, reject) => {
//get our html
axios.get(url)
.then(resp => {
//html
const html = resp.data;
//load into a $
const $ = cheerio.load(html);
//find ourself a img
const retURL = nodeURL.resolve(url,$("body").find("img")[0].attribs.src);
resolve(retURL);
})
.catch(err => {
reject(err);
});
});
}
现在我有一个看起来像这样的函数:
static getPageImg(url) {
return new Promise((resolve, reject) => {
//get our html
axios.get(url)
.then(resp => {
//html
const html = resp.data;
//load into a $
const $ = cheerio.load(html);
//find ourself a img
const src = url + "/" + $("body").find("img")[0].attribs.src;
//make sure there are no extra slashes
resolve(src.replace(/([^:]\/)\/+/g, ""));
})
.catch(err => {
reject(err);
});
});
}
这将处理页面使用图像 link 的相对路径并且主机名与提供的 URL 相同的一般情况。
然而, 大多数时候 URL 方案会更复杂,例如 URL 可能是 Whosebug。com/something/asdasd 而我需要的是获得 Whosebug。com/someimage link。或者更有趣的情况是使用 CDN 并且图像来自单独的服务器。例如,如果我想 link 来自 imgur 的东西,我会给出一个 link,例如:http://imgur.com/gallery/epqDj. But the actual location of the image is at http://i.imgur.com/pK0thAm.jpg 网站的子域。更有趣的是,如果我要获取 src 属性,我将拥有:“//i.imgur.com/pK0thAm.jpg”。
现在我想一定有一种简单的方法来获取此图像,因为浏览器可以非常快速且轻松地执行 "open window in new tab" 所以我想知道是否有人知道除了编写之外的简单方法一个可以处理所有这些情况的大函数。
谢谢!
这是我的函数,它最终适用于我所有使用 URL 类型内置节点的测试用例。我只好使用解析函数。
static getPageImg(url) {
return new Promise((resolve, reject) => {
//get our html
axios.get(url)
.then(resp => {
//html
const html = resp.data;
//load into a $
const $ = cheerio.load(html);
//find ourself a img
const retURL = nodeURL.resolve(url,$("body").find("img")[0].attribs.src);
resolve(retURL);
})
.catch(err => {
reject(err);
});
});
}