To adapt your JavaScript script for use in Google Apps Script (GAS), you can utilize the CheerioGS library, which is a port of Cheerio tailored for GAS. This will allow you to parse and manipulate HTML similarly to how you do in a browser environment.
-
Add the CheerioGS Library to Your GAS Project
Unfortunately, Cheerio isn't natively supported in GAS, but you can use the CheerioGS library as an alternative. To add it:
-
Method 1: Including CheerioGS Code Directly
- Go to the CheerioGS GitHub repository and copy the contents of the
cheerio.gs file.
- In your GAS project, create a new script file (e.g.,
Cheerio.gs) and paste the copied code.
-
Method 2: Using an Existing GAS Library
As of now, there's no published GAS library ID for CheerioGS, so including the code directly is the recommended approach.
-
Write the Google Apps Script Function
Here's how you can translate your browser-based JavaScript code to GAS using CheerioGS:
/**
* Fetches image URLs from an Amazon listings page where each listing has more than one rating.
*
* @param {string} pageUrl - The URL of the Amazon listings page.
* @return {Array<string>} - An array of image URLs.
*/
function getAmazonListingImageUrls(pageUrl) {
if (!pageUrl) {
throw new Error('Please provide a valid Amazon page URL.');
}
// Fetch the HTML content of the page
const response = UrlFetchApp.fetch(pageUrl, {
headers: {
// Setting a user agent can help avoid being blocked by Amazon
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) ' +
'AppleWebKit/537.36 (KHTML, like Gecko) ' +
'Chrome/58.0.3029.110 Safari/537.3'
}
});
const html = response.getContentText();
// Initialize Cheerio with the fetched HTML
const $ = Cheerio.load(html);
const imageUrls = [];
// Select all listing items
$('.s-result-item').each(function() {
const listing = $(this);
// Find the span with aria-label ending with "ratings"
const ratingElement = listing.find('span[aria-label$="ratings"]');
if (ratingElement.length > 0) {
const ratingText = ratingElement.attr('aria-label');
const ratingNumberMatch = ratingText.match(/(\d+)/);
if (ratingNumberMatch) {
const ratingNumber = parseInt(ratingNumberMatch[1], 10);
if (ratingNumber > 1) {
const imgElement = listing.find('.s-image');
if (imgElement.length > 0) {
const imgSrc = imgElement.attr('src');
if (imgSrc) {
imageUrls.push(imgSrc);
}
}
}
}
}
});
return imageUrls;
}
-
Usage Example
To use the above function, you can create another function or use it within the GAS editor's Run feature. Here's an example of how to call it and log the results:
function testGetAmazonListingImageUrls() {
const amazonPageUrl = 'https://www.amazon.com/s?k=your+search+query'; // Replace with your desired Amazon search URL
const imageUrls = getAmazonListingImageUrls(amazonPageUrl);
Logger.log(imageUrls);
}
- Steps to Execute:
- Save your script.
- Click on the
testGetAmazonListingImageUrls function.
- Run the function (
► Run button).
- Authorize the script if prompted.
- Check the Logs (
View > Logs) to see the extracted image URLs.
-
Important Considerations
-
Legal and Ethical Implications: Scraping Amazon or any other website may violate their Terms of Service. Ensure you have the right to scrape the data and use it appropriately.
-
Rate Limiting and IP Blocking: Amazon employs various anti-scraping technologies. To minimize the risk of being blocked:
- Use appropriate
User-Agent headers as shown in the script.
- Implement delays between requests if making multiple fetches.
- Avoid making high-frequency requests.
-
Dynamic Content: Amazon pages might use JavaScript to load content dynamically. Since GAS fetches the raw HTML, some content may not be present. If you encounter issues with missing elements, consider using a headless browser service or APIs that can render JavaScript.
-
Error Handling: Enhance the script with better error handling to manage scenarios like network failures, changes in Amazon’s HTML structure, or unexpected content.
-
Sample Output
After running the testGetAmazonListingImageUrls function, the Logs might display something like:
[
"https://images-na.ssl-images-amazon.com/images/I/51Zymoq7UnL._AC_SY400_.jpg",
"https://images-na.ssl-images-amazon.com/images/I/41as+WafrFL._AC_SY400_.jpg",
...
]
-
Extending Functionality
Depending on your needs, you can extend this script to extract additional information such as product titles, prices, ratings, and more. Here's a brief example of extracting product titles alongside image URLs:
function getAmazonListingDetails(pageUrl) {
if (!pageUrl) {
throw new Error('Please provide a valid Amazon page URL.');
}
const response = UrlFetchApp.fetch(pageUrl, {
headers: {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) ' +
'AppleWebKit/537.36 (KHTML, like Gecko) ' +
'Chrome/58.0.3029.110 Safari/537.3'
}
});
const html = response.getContentText();
const $ = Cheerio.load(html);
const listings = [];
$('.s-result-item').each(function() {
const listing = $(this);
const ratingElement = listing.find('span[aria-label$="ratings"]');
if (ratingElement.length > 0) {
const ratingText = ratingElement.attr('aria-label');
const ratingNumberMatch = ratingText.match(/(\d+)/);
if (ratingNumberMatch) {
const ratingNumber = parseInt(ratingNumberMatch[1], 10);
if (ratingNumber > 1) {
const imgElement = listing.find('.s-image');
const titleElement = listing.find('h2 .a-link-normal');
const imgSrc = imgElement.attr('src');
const title = titleElement.text().trim();
if (imgSrc && title) {
listings.push({
title: title,
imageUrl: imgSrc
});
}
}
}
}
});
return listings;
}
function testGetAmazonListingDetails() {
const amazonPageUrl = 'https://www.amazon.com/s?k=your+search+query'; // Replace with your desired Amazon search URL
const listings = getAmazonListingDetails(amazonPageUrl);
Logger.log(listings);
}
This script will log an array of objects containing both the product titles and image URLs.
-
Final Notes
-
Maintenance: Amazon frequently updates its website structure, which may break your scraping logic. Regularly verify and update your selectors as needed.
-
Performance: For large-scale scraping, consider implementing caching mechanisms or utilizing Google Sheets to store and manage the extracted data.
By following the steps above, you can successfully adapt your browser-based JavaScript scraping script to Google Apps Script using the CheerioGS library. Always ensure to respect website policies and legal guidelines when scraping data.