To achieve your goal of extracting image URLs from Amazon listings using Google Apps Script, you'll need to adapt your existing JavaScript code (which works in the browser) to work in a server-side environment. Google Apps Script doesn't have a DOM, so we'll need to parse the HTML response manually.
Here's a step-by-step guide along with the complete script to help you accomplish this:
-
Fetch the Amazon Page:
- Use
UrlFetchApp.fetch to retrieve the HTML content of the Amazon page.
- To mimic human-like behavior, set appropriate request headers, especially the
User-Agent.
-
Parse the HTML Content:
- Since Google Apps Script doesn't provide a DOM parser, we'll use regular expressions to extract the necessary information.
- We'll look for
.s-result-item elements, check for the presence of ratings, and extract the image URLs.
-
Handle Amazon's Anti-Scraping Measures:
- Be mindful of Amazon's Terms of Service regarding scraping.
- Excessive or aggressive scraping can lead to IP blocking or legal issues.
-
Return the Extracted Image URLs:
- The function will return an array of image URLs that meet your criteria.
Complete Google Apps Script
/**
* Fetches image URLs from an Amazon listings page where listings have more than 1 rating.
*
* @param {string} pageUrl - The URL of the Amazon listings page.
* @return {Array<string>} An array of image URLs.
*/
function getAmazonListingImageUrls(pageUrl) {
// Validate the URL
if (!pageUrl || typeof pageUrl !== 'string') {
throw new Error('A valid Amazon page URL must be provided.');
}
// Set up request headers to mimic a real browser
const headers = {
'User-Agent':
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) ' +
'AppleWebKit/537.36 (KHTML, like Gecko) ' +
'Chrome/112.0.0.0 Safari/537.36',
'Accept-Language': 'en-US,en;q=0.9',
};
// Options for UrlFetchApp
const options = {
headers: headers,
muteHttpExceptions: true, // Prevent script from terminating on HTTP errors
};
try {
// Fetch the page content
const response = UrlFetchApp.fetch(pageUrl, options);
const responseCode = response.getResponseCode();
if (responseCode !== 200) {
throw new Error(`Failed to fetch the page. HTTP Response Code: ${responseCode}`);
}
const html = response.getContentText();
// Use regular expressions to parse the HTML content
// This regex matches each '.s-result-item' block
const itemRegex = /<div[^>]+class="[^"]*\bs-result-item\b[^"]*"[^>]*>([\s\S]*?)<\/div>/g;
let match;
const imageUrls = [];
while ((match = itemRegex.exec(html)) !== null) {
const itemHtml = match[1];
// Regex to find the aria-label for ratings
const ratingRegex = /<span[^>]+aria-label="([\d,]+)\s+ratings?"[^>]*>/i;
const ratingMatch = ratingRegex.exec(itemHtml);
if (ratingMatch) {
// Extract the number of ratings, removing commas
const ratingNumber = parseInt(ratingMatch[1].replace(/,/g, ''), 10);
if (ratingNumber > 1) {
// Regex to find the image src in '.s-image'
const imageRegex = /<img[^>]+class="[^"]*\bs-image\b[^"]*"[^>]+src="([^"]+)"[^>]*>/i;
const imageMatch = imageRegex.exec(itemHtml);
if (imageMatch && imageMatch[1]) {
imageUrls.push(imageMatch[1]);
}
}
}
}
return imageUrls;
} catch (error) {
Logger.log(`Error: ${error.message}`);
return [];
}
}
/**
* Example usage of the getAmazonListingImageUrls function.
*/
function exampleUsage() {
const amazonPageUrl = 'https://www.amazon.com/s?k=your+search+term';
const images = getAmazonListingImageUrls(amazonPageUrl);
if (images.length > 0) {
images.forEach((url, index) => {
Logger.log(`Image ${index + 1}: ${url}`);
});
} else {
Logger.log('No images found or an error occurred.');
}
}
Explanation of the Script
-
Function getAmazonListingImageUrls:
- Parameters:
pageUrl: The URL of the Amazon search results or listings page.
- Process:
- Validation: Ensures that a valid URL is provided.
- Headers: Sets the
User-Agent and Accept-Language headers to mimic a real browser, making the request appear more human-like.
- Fetching Content: Uses
UrlFetchApp.fetch to retrieve the HTML content of the page.
- Parsing HTML:
- Uses regular expressions to locate each
.s-result-item block.
- Within each block, it searches for a
<span> with an aria-label ending with "ratings" to determine the number of ratings.
- If the number of ratings is greater than 1, it extracts the
src attribute of the image with class .s-image.
- Error Handling: Logs any errors encountered during the fetch or parsing process and returns an empty array in such cases.
- Return Value: An array of image URLs that meet the specified criteria.
-
Function exampleUsage:
- Demonstrates how to use the
getAmazonListingImageUrls function.
- Replace
'https://www.amazon.com/s?k=your+search+term' with the actual Amazon URL you wish to scrape.
- Logs the extracted image URLs to the Apps Script Logger.
Important Considerations
Testing the Script
-
Open Google Apps Script:
-
Paste the Script:
- Copy the provided script into the editor.
-
Run exampleUsage:
- Replace the
amazonPageUrl with a valid Amazon listings URL.
- Run the
exampleUsage function.
- Check the Logs (
View > Logs) to see the extracted image URLs.
-
Deploy or Schedule:
- You can set up triggers to run this script periodically or integrate it with other Google Workspace apps as needed.
Conclusion
While Google Apps Script provides powerful tools for automation, scraping large or complex websites like Amazon can be challenging due to dynamic content and anti-scraping measures. Always ensure that your scraping activities comply with the website’s policies and legal guidelines.