Fetching data from websites like Amazon can be challenging due to their robust anti-scraping measures, which often result in errors like 503 Service Unavailable when making direct server-side requests. Using a proxy like allorigins.win can help bypass these restrictions, but as you've experienced, it may introduce significant latency.
Here are several strategies to improve the performance and reliability of your Google Apps Script for fetching and parsing Amazon listings:
1. Optimize Direct Fetch with Enhanced Headers
Sometimes, web servers like Amazon block requests that don't closely mimic browser behavior. By setting more comprehensive headers, you can make your request appear more legitimate and potentially avoid 503 errors.
Updated getListingUrls Function:
function getListingUrls(url) {
const options = {
'muteHttpExceptions': true,
'followRedirects': true,
'headers': {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) ' +
'AppleWebKit/537.36 (KHTML, like Gecko) ' +
'Chrome/91.0.4472.124 Safari/537.36',
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
'Accept-Language': 'en-US,en;q=0.9',
'Connection': 'keep-alive',
'Referer': 'https://www.amazon.com/'
},
'timeout': 30000 // 30 seconds timeout
};
try {
const response = UrlFetchApp.fetch(url, options);
const responseCode = response.getResponseCode();
if (responseCode !== 200) {
throw new Error('Failed to fetch the page. Response code: ' + responseCode);
}
const htmlContent = response.getContentText();
const $ = Cheerio.load(htmlContent);
const imageUrls = $('.s-result-item')
.map((index, item) => {
const ratingElement = $(item).find('span[aria-label$="ratings"]');
if (ratingElement.length > 0) {
const ratingText = ratingElement.attr('aria-label');
const ratingNumber = parseInt(ratingText, 10);
if (ratingNumber > 1) {
const imgElement = $(item).find('.s-image');
if (imgElement.length > 0 && imgElement.attr('src')) {
return imgElement.attr('src');
}
}
}
return null;
})
.get()
.filter(Boolean);
return imageUrls;
} catch (error) {
console.error('Error fetching or parsing the page:', error);
return [];
}
}
function testFunction() {
const url = "https://www.amazon.com/s?k=nurse+t-shirt&i=fashion-novelty&ref=nb_sb_noss";
const results = getListingUrls(url);
console.log(results);
}
Key Enhancements:
- Additional Headers: Added
Accept, Accept-Language, Connection, and Referer headers to better mimic a real browser request.
- Timeout Setting: Increased the timeout to handle longer response times gracefully.
- Direct Fetch: Attempting a direct fetch without using
allorigins.win to reduce latency.
Potential Outcome:
These changes may help bypass Amazon's basic anti-scraping protections. However, Amazon employs sophisticated measures (like IP rate limiting and JavaScript challenges) which may still result in 503 errors or block your requests after multiple attempts.
2. Use a More Reliable CORS Proxy
If direct fetching continues to fail, consider switching to a more reliable or faster proxy service. Some alternatives include:
- CORS Anywhere: A popular proxy that allows you to bypass CORS restrictions. You may need to deploy your own instance to ensure reliability and performance.
- ScraperAPI: A paid service that handles proxies, browsers, and CAPTCHAs for you.
- Bright Data: Another premium proxy service with extensive infrastructure.
Example with CORS Anywhere:
function getListingUrlsWithCorsAnywhere(url) {
const proxyUrl = 'https://cors-anywhere.herokuapp.com/'; // Replace with your own proxy if necessary
const targetUrl = encodeURIComponent(url);
const fullUrl = proxyUrl + url;
const options = {
'muteHttpExceptions': true,
'headers': {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) ' +
'AppleWebKit/537.36 (KHTML, like Gecko) ' +
'Chrome/91.0.4472.124 Safari/537.36',
'Origin': 'https://www.amazon.com'
},
'timeout': 30000
};
// Note: You might need to handle API keys or rate limits depending on the proxy service
try {
const response = UrlFetchApp.fetch(fullUrl, options);
// The rest of the parsing logic remains the same
// ...
} catch (error) {
console.error('Error fetching through proxy:', error);
return [];
}
}
Considerations:
- Costs: Premium proxies usually charge based on usage.
- Reliability: Higher quality proxies offer better uptime and speed.
- Maintenance: You might need to handle API keys, rotate proxies, and manage rate limits.
3. Implement Caching to Reduce Fetch Frequency
If your script frequently requests the same URLs, implementing a caching mechanism can significantly improve performance by reducing the number of external fetches.
Example Using Script Properties for Caching:
function getListingUrlsCached(url) {
const cache = CacheService.getScriptCache();
const cachedData = cache.get(url);
if (cachedData) {
console.log('Returning cached data');
return JSON.parse(cachedData);
}
const imageUrls = getListingUrls(url); // Use the optimized direct fetch function
if (imageUrls.length > 0) {
cache.put(url, JSON.stringify(imageUrls), 21600); // Cache for 6 hours
}
return imageUrls;
}
function testCachedFunction() {
const url = "https://www.amazon.com/s?k=nurse+t-shirt&i=fashion-novelty&ref=nb_sb_noss";
const results = getListingUrlsCached(url);
console.log(results);
}
Benefits:
- Reduced Latency: Subsequent requests for the same URL retrieve data from the cache.
- Lower External Calls: Minimizes dependency on external proxies or direct fetching.
Limitations:
- Stale Data: Cached data may not reflect the most recent changes on the target website.
- Storage Limits: Google Apps Script cache has storage limits (100KB per entry).
4. Use Google Cloud Functions as a Custom Proxy
If existing proxies don't meet your performance needs, consider creating a custom proxy using Google Cloud Functions or Google Cloud Run. This allows you to have more control over the fetching process and potentially achieve lower latency.
Steps:
-
Set Up a Google Cloud Project:
-
Deploy a Simple Proxy Function:
- Write a simple HTTP function that takes a target URL as a parameter and returns the fetched content.
Example in Node.js:
const fetch = require('node-fetch');
exports.proxy = async (req, res) => {
const targetUrl = req.query.url;
if (!targetUrl) {
res.status(400).send('Missing url parameter');
return;
}
try {
const response = await fetch(targetUrl, {
headers: {
'User-Agent': req.get('User-Agent') || 'Mozilla/5.0',
'Accept': req.get('Accept') || '*/*',
'Accept-Language': req.get('Accept-Language') || 'en-US,en;q=0.9'
}
});
const content = await response.text();
res.status(response.status).send(content);
} catch (error) {
res.status(500).send('Error fetching the target URL');
}
};
-
Deploy the Function:
- Deploy the function and obtain the endpoint URL.
-
Update Your Apps Script to Use the Custom Proxy:
function getListingUrlsCustomProxy(url) {
const proxyEndpoint = 'https://YOUR_CLOUD_FUNCTION_URL/proxy';
const fullUrl = `${proxyEndpoint}?url=${encodeURIComponent(url)}`;
const options = {
'muteHttpExceptions': true,
'headers': {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) ' +
'AppleWebKit/537.36 (KHTML, like Gecko) ' +
'Chrome/91.0.4472.124 Safari/537.36',
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
'Accept-Language': 'en-US,en;q=0.9'
},
'timeout': 30000
};
try {
const response = UrlFetchApp.fetch(fullUrl, options);
if (response.getResponseCode() !== 200) {
throw new Error('Failed to fetch the page. Response code: ' + response.getResponseCode());
}
const htmlContent = response.getContentText();
const $ = Cheerio.load(htmlContent);
const imageUrls = $('.s-result-item')
.map((index, item) => {
const ratingElement = $(item).find('span[aria-label$="ratings"]');
if (ratingElement.length > 0) {
const ratingText = ratingElement.attr('aria-label');
const ratingNumber = parseInt(ratingText, 10);
if (ratingNumber > 1) {
const imgElement = $(item).find('.s-image');
if (imgElement.length > 0 && imgElement.attr('src')) {
return imgElement.attr('src');
}
}
}
return null;
})
.get()
.filter(Boolean);
return imageUrls;
} catch (error) {
console.error('Error fetching or parsing the page via custom proxy:', error);
return [];
}
}
function testCustomProxyFunction() {
const url = "https://www.amazon.com/s?k=nurse+t-shirt&i=fashion-novelty&ref=nb_sb_noss";
const results = getListingUrlsCustomProxy(url);
console.log(results);
}
Advantages:
- Better Performance: Potentially lower latency compared to third-party proxies.
- Customization: Full control over request handling, headers, and error management.
- Scalability: Google Cloud Functions can scale with your needs.
Considerations:
- Cost: While Google Cloud Functions offers a free tier, extensive usage may incur costs.
- Setup Complexity: Requires familiarity with Google Cloud services and deploying serverless functions.
5. Leverage Caching and Parallel Processing
To further enhance performance:
- Implement Batch Processing: If you need to fetch multiple URLs, run requests in parallel where possible.
- Use Caching Services: Utilize more advanced caching mechanisms or external storage (like Firebase) for persistent and shared caches.
6. Respect Website Policies and Use Official APIs
Before proceeding, ensure that your scraping activities comply with Amazon's Terms of Service. Unauthorized scraping can lead to IP bans or legal consequences.
Alternative: Amazon Product Advertising API
If your goal is to retrieve product information, consider using Amazon's Product Advertising API. This official API provides structured access to Amazon product data and is designed for applications like yours.
Benefits:
- Reliable Data Access: Direct access to Amazon's product data without scraping.
- Performance: Generally faster and more reliable than scraping.
- Compliance: Aligns with Amazon's policies and reduces the risk of legal issues.
Note: Usage of the API may require affiliation with the Amazon Associates program and adherence to specific usage guidelines.
Final Recommendations
-
Start with Enhanced Direct Fetching:
- Implement more comprehensive headers to improve the success rate of direct
UrlFetchApp.fetch requests.
-
Implement Caching:
- Use Google Apps Script’s caching services to store and reuse fetched data, reducing the number of external requests.
-
Explore Reliable Proxy Solutions:
- If direct fetching remains unreliable, consider switching to a more performant proxy service or setting up your own proxy using Google Cloud Functions.
-
Consider Official APIs:
- Evaluate whether Amazon’s Product Advertising API meets your needs, providing a more robust and compliant solution.
-
Monitor and Optimize:
- Continuously monitor the performance and reliability of your fetching mechanism.
- Optimize your parsing logic and reduce unnecessary data processing where possible.
By implementing these strategies, you should be able to enhance the performance and reliability of your Google Apps Script when fetching and parsing Amazon listings.