开发者

travesersing the dom with inexact parameters

开发者 https://www.devze.com 2022-12-17 13:00 出处:网络
I want to grab the image src on a product page in a e commerce website. I\'m writing this as a bookmarklet, so I\'d like the code to work universally as possible.

I want to grab the image src on a product page in a e commerce website.

I'm writing this as a bookmarklet, so I'd like the code to work universally as possible.

I've noticed that there are only two reoccurring factors in the product image tag among top e-commerce websites 开发者_开发技巧(amazon, bestbuy ect.): border=0 and 180<width&height<400. So how could I write a selector that would give me the srcof the first img element on the page with no border and width & height between 180 and 400 px? Or is there a better way of doing this?

P.S. since I'm trying to keep the bookmarklet as light as possible, I don't want to use any libraries (jquery, yui etc)


I don't feel like I fully understand your question, but here I go anyways!

Do you mean something like...

function findYouImg() {
   var imgs = document.getElementsByTagName('img');
   for(var i=0; i<imgs.length; i++) {
      if(imgs[i].border=='' && imgs[i].width>180 && imgs[i].height<400 ) {
         return imgs[i];
      }
   }
}

Or are you refering to external CSS properties when you speak of border, width and height?


If you don't have to support browsers which don't implement document.evaluate, another approach would be to look at each site you want to support, create an XPATH expression which uniquely identifies the product image and use a lookup based on the domain:

var productImageXPath = (function() {
  var xpaths = {
    'amazon.com': "//img[@id='prodImage']",
    'bestbuy.com': "//div[@id='imagepreview']/img"
  };
  function endsWith(s1, s2) {
    return (s1.indexOf(s2) == s1.length - s2.length);
  };
  return function(host) {
    for (attr in xpaths) {
      if (endsWith(host, attr)) {
        return xpaths[attr];
      }
    }
    return null;
  };
})();
var xpath = productImageXPath(location.host);
if (xpath) {
  var img = document.evaluate(xpath, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
  if (img) {
    console.log(img.src);
  }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消