Created
May 21, 2024 15:07
-
-
Save brynnb/6c6a88573e99bbe56b9b1fabe53e00a5 to your computer and use it in GitHub Desktop.
This bookmarklet allows you to rearrange Amazon search results by the lowest to highest price per unit of measure. It extracts price and unit information from each search result, standardizes units to milliliters, calculates the price per milliliter, and then reorders the items accordingly.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
javascript:(function(){function convertToMilliliters(value,unit){switch(unit.toLowerCase()){case 'fl oz':case 'fl. oz':return value*29.5735;case 'oz':return value*29.5735;case 'ml':return value;case 'l':return value*1000;default:console.warn(`Unrecognized unit: ${unit}`);return null;}}function parsePriceAndUnit(element){console.log('Parsing price and unit from element:', element);let priceText=element.querySelector('.a-offscreen').textContent.replace(/[^0-9.]/g,'');let match=element.textContent.match(/\/([a-zA-Z\s.]+)/);console.log(priceText,match);if(!match){console.warn('No unit match found in element:', element);return null;}let unitText=match[1].trim();return{price:parseFloat(priceText),unit:unitText};}var pricePerUnitElements=document.querySelectorAll('[class*="a-price a-text-price"]');var items=[];pricePerUnitElements.forEach(el=>{let parentContainer=el.closest('[data-component-type="s-search-result"]');if(parentContainer){let priceAndUnitParent=el.closest('.a-size-base.a-color-secondary');if(priceAndUnitParent){let priceAndUnit=parsePriceAndUnit(priceAndUnitParent);if(priceAndUnit){console.log('Price and unit:',priceAndUnit);let{price,unit}=priceAndUnit;let milliliters=convertToMilliliters(1,unit);if(milliliters!==null){let pricePerMilliliter=price/milliliters;items.push({container:parentContainer,pricePerMilliliter:pricePerMilliliter});}}}}else{console.warn('No parent container found for element:',el);}});items.sort((a,b)=>a.pricePerMilliliter-b.pricePerMilliliter);var parentElement=document.querySelector('.s-main-slot');items.forEach(item=>{parentElement.appendChild(item.container);});console.log('Items rearranged by lowest to highest price per unit of measure.');})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment