I want to get images URLs of listings from Amazon. I have this JavaScript script it is working fine in browser console now I want to use it in google app script. you can use cheerio library. We will pass page URL as arg. the request should be as human as possible.
Here is the code
const getListingImagesWithMultipleRatings = () => {
const listingItems = document.querySelectorAll('.s-result-item');
To convert your browser-based JavaScript script for extracting Amazon listing image URLs into a Google Apps Script (GAS) project, you'll need to account for the differences between client-side and server-side environments. While your original script uses DOM manipulation methods available in the browser, GAS requires server-side HTTP requests and HTML parsing.
Although you mentioned using the Cheerio library, integrating Cheerio directly into GAS can be challenging because GAS doesn't support Node.js modules out of the box. However, you can achieve similar functionality using regular expressions or by including a lightweight HTML parsing library compatible with GAS.
Below, I'll guide you through creating a GAS function that:
Fetches the Amazon page with appropriate headers to mimic a human browser.
Parses the HTML to extract image URLs from listings with more than one rating.
Replace the default myFunction with your custom function (e.g., getAmazonListingImageUrls).
Step 2: Writing the GAS Function
Since integrating Cheerio directly isn't straightforward, we'll use regular expressions to parse the HTML content. Here's a complete script that performs the desired task:
javascript
/**
* Fetches image URLs from Amazon listings with more than one rating.
*
* @param {string} pageUrl - The URL of the Amazon search results page.
* @return {Array<string>} - An array of image URLs.
*/
function getAmazonListingImageUrls(pageUrl) {
// Define headers to mimic a real browser request
var headers = {
'User-Agent': getRandomUserAgent(),
'Accept-Language': 'en-US,en;q=0.9',
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
'Connection': 'keep-alive',
};
// Configure fetch options
var options = {
'method': 'get',
'headers': headers,
'muteHttpExceptions': true, // Continue script even if fetch fails
};
try {
// Fetch the Amazon page
var response = UrlFetchApp.fetch(pageUrl, options);
var statusCode = response.getResponseCode();
if (statusCode !== 200) {
throw new Error('Failed to fetch the page. Status code: ' + statusCode);
}
var html = response.getContentText();
// Parse the HTML and extract image URLs
var imageUrls = extractImageUrls(html);
return imageUrls;
} catch (error) {
Logger.log('Error: ' + error.message);
return [];
}
}
/**
* Generates a random User-Agent string from a predefined list.
*
* @return {string} - A User-Agent string.
*/
function getRandomUserAgent() {
var userAgents = [
// Chrome
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) ' +
'AppleWebKit/537.36 (KHTML, like Gecko) ' +
'Chrome/91.0.4472.124 Safari/537.36',
// Firefox
'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:89.0) ' +
'Gecko/20100101 Firefox/89.0',
// Safari
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) ' +
'AppleWebKit/605.1.15 (KHTML, like Gecko) ' +
'Version/14.1.1 Safari/605.1.15',
// Edge
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) ' +
'AppleWebKit/537.36 (KHTML, like Gecko) ' +
'Chrome/91.0.4472.124 Safari/537.36 Edg/91.0.864.64',
// Add more User-Agents as needed
];
var index = Math.floor(Math.random() * userAgents.length);
return userAgents[index];
}
/**
* Extracts image URLs from the Amazon page HTML content.
*
* @param {string} html - The HTML content of the Amazon page.
* @return {Array<string>} - An array of image URLs.
*/
function extractImageUrls(html) {
var imageUrls = [];
// Regex to match each listing item
var listingRegex = /<div[^>]+class="[^"]*\bs-result-item\b[^"]*"[^>]*>([\s\S]*?)<\/div>/g;
var listingMatch;
while ((listingMatch = listingRegex.exec(html)) !== null) {
var itemHtml = listingMatch[1];
// Regex to find the rating element
var ratingRegex = /<span[^>]*aria-label="(\d+(\.\d+)?)\s+ratings?"[^>]*>/i;
var ratingMatch = ratingRegex.exec(itemHtml);
if (ratingMatch) {
var ratingNumber = parseFloat(ratingMatch[1]);
if (ratingNumber > 1) {
// Regex to find the image element
var imgRegex = /<img[^>]+class="[^"]*\bs-image\b[^"]*"[^>]*src="([^"]+)"[^>]*>/i;
var imgMatch = imgRegex.exec(itemHtml);
if (imgMatch && imgMatch[1]) {
var imgSrc = imgMatch[1];
imageUrls.push(imgSrc);
}
}
}
}
return imageUrls;
}
/**
* Test function to demonstrate usage.
*/
function testGetAmazonListingImageUrls() {
var pageUrl = 'https://www.amazon.com/s?k=laptops'; // Replace with your desired Amazon search URL
var imageUrls = getAmazonListingImageUrls(pageUrl);
// Log the image URLs
imageUrls.forEach(function(url, index) {
Logger.log((index + 1) + ': ' + url);
});
}
Step 3: Understanding the Script
Headers Configuration:
User-Agent: Randomly selects a User-Agent string from a predefined list to mimic different browsers, reducing the chance of being blocked.
Accept-Language, Accept, Connection: These headers further emulate a real browser's request.
Fetching the Page:
UrlFetchApp.fetch: Performs an HTTP GET request to the specified Amazon page URL with the defined headers.
Error Handling: Checks if the response status code is 200 OK. If not, it logs an error and returns an empty array.
Parsing the HTML:
Regular Expressions: Utilizes regex patterns to extract relevant sections of the HTML.
Listing Regex: Identifies each listing item by matching <div> elements with the s-result-item class.
Rating Regex: Within each listing, finds the <span> element that contains the rating information using the aria-label attribute.
Image Regex: If the rating is greater than 1, it extracts the src attribute of the <img> element with the s-image class, which holds the product image URL.
Testing the Function:
testGetAmazonListingImageUrls: A test function that you can run from the Apps Script editor. It fetches image URLs from a sample Amazon search URL and logs them.
Step 4: Running the Script
Set Up the Test Function:
Ensure the pageUrl in testGetAmazonListingImageUrls points to a valid Amazon search results page.
Execute the Test:
Save the script.
Select testGetAmazonListingImageUrls from the dropdown menu in the Apps Script editor.
Click the Run button.
Check the Logs:
After the script runs, go to View > Logs to see the extracted image URLs.
Step 5: Important Considerations
Terms of Service:
Amazon's Policies: Scraping Amazon may violate their Terms of Service. Ensure you have the right to scrape their data and use it responsibly.
Dynamic Content and JavaScript Rendering:
Limitations: Amazon pages often use dynamic content rendering with JavaScript. Since GAS fetches the raw HTML without executing JavaScript, some elements might not be present in the fetched HTML. This can limit the effectiveness of regex-based parsing.
Reliability of Regex Parsing:
Fragility: Regular expressions can be brittle, especially when parsing complex and frequently changing HTML structures like Amazon's. If Amazon updates their HTML layout, the regex patterns may need adjustments.
Rate Limiting and Access Restrictions:
Avoid Overloading: Make sure to implement rate limiting if you're scraping multiple pages to avoid being blocked.
CAPTCHAs and Blocking: Amazon may detect and block automated scraping, especially if requests are frequent or come from the same IP.
Alternative Approaches:
Headless Browsers: For more reliable scraping of dynamic content, consider using headless browsers like Puppeteer in environments that support Node.js.
Third-Party Services: Use web scraping services or APIs that handle dynamic content and provide structured data.
Step 6: Enhancements and Best Practices
Advanced HTML Parsing:
Libraries: While integrating Cheerio directly into GAS is challenging, consider using other lightweight parsing libraries or splitting the task into smaller parts if necessary.
Caching Results:
Efficiency: Implement caching mechanisms to store results and reduce redundant requests, improving efficiency and reducing the likelihood of being blocked.
Error Handling and Logging:
Robustness: Enhance error handling to manage different failure scenarios gracefully and provide insightful logs for troubleshooting.
Pagination Support:
Extended Scraping: If you need to scrape multiple pages, handle pagination by modifying the pageUrl accordingly and iterating through the desired number of pages.
Data Storage:
Saving Results: Store the extracted image URLs in Google Sheets, Google Drive, or other storage solutions for further processing or analysis.
Conclusion
While Google Apps Script provides a convenient platform for automating tasks and processing data, web scraping—especially from complex and dynamic websites like Amazon—can be challenging due to limitations in HTML parsing and the need to mimic human behavior closely. The provided script offers a foundational approach using regex-based parsing, which may work for simple and consistent HTML structures. However, for more robust and reliable scraping, especially involving dynamic content, consider using more specialized tools and environments tailored for web scraping.
Disclaimer: Be sure to comply with Amazon's Terms of Service and respect their policies regarding automated access and data usage.