Sure! To clarify your request:
- You have a list of page URLs in Sheet1.
- For each URL in Sheet1, you want to extract all image URLs found on that page.
- Then, in Sheet2, you want:
- Column A: The source page URL.
- Column B: The image URL from that page.
- Column C: The image alt text for that image.
- Each image for a source page URL should be listed in its own row (vertically).
Is this correct?
I can write a script (e.g., Google Apps Script) for Google Sheets that:
- Reads all URLs from Sheet1 (say A1:A).
- For each URL, fetches the page content.
- Parses the HTML for
<img> tags.
- Extracts the
src and alt attributes for each image.
- Writes the results to Sheet2 as described above.
Would you like me to proceed with the Google Apps Script? Or do you prefer a Python script? And is this for a specific environment?
If Google Sheets/Apps Script is fine, here is a sample code:
function extractImages() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet1 = ss.getSheetByName('Sheet1');
var sheet2 = ss.getSheetByName('Sheet2');
// Clear previous data on Sheet2
sheet2.clearContents();
// Write header row
sheet2.appendRow(['Page URL', 'Image URL', 'Image Alt Text']);
// Get URLs from Sheet1 (assume in column A, starting row 1)
var urls = sheet1.getRange('A1:A' + sheet1.getLastRow()).getValues();
var urlFetchOpts = {
muteHttpExceptions: true
};
for (var i = 0; i < urls.length; i++) {
var pageUrl = urls[i][0];
if (pageUrl) {
try {
var response = UrlFetchApp.fetch(pageUrl, urlFetchOpts);
var content = response.getContentText();
// Create an HTML document from the content (use XmlService)
var imgMatches = content.match(/<img [^>]*src=["']([^"']+)["'][^>]*>/gi);
if (imgMatches) {
imgMatches.forEach(function(imgTag){
var srcMatch = imgTag.match(/src=["']([^"']+)["']/i);
var altMatch = imgTag.match(/alt=["']([^"']*)["']/i);
var imgSrc = srcMatch ? srcMatch[1] : '';
var altText = altMatch ? altMatch[1] : '';
// Resolve relative URLs to absolute URLs
if (imgSrc && imgSrc.indexOf('http') !== 0) {
try {
var base = pageUrl.match(/^(https?:\/\/[^\/]+)/)[1];
if (imgSrc.indexOf('/') === 0) {
imgSrc = base + imgSrc;
} else {
// Relative URL without starting slash; concatenate carefully
var urlParts = pageUrl.split('/');
urlParts.pop(); // Remove last segment (page file)
imgSrc = urlParts.join('/') + '/' + imgSrc;
}
} catch(e) {
// If fails, leave as is
}
}
sheet2.appendRow([pageUrl, imgSrc, altText]);
});
}
} catch(err) {
Logger.log('Error fetching ' + pageUrl + ': ' + err);
// Could write a line to Sheet2 to indicate error if desired
}
}
}
}
How to use:
- Open your Google Sheet with Sheet1 containing page URLs in column A.
- Go to Extensions > Apps Script.
- Paste the above function into the script editor.
- Save the project.
- Run
extractImages function.
- Authorize the script on the first run.
- Check Sheet2 for results.
Let me know if you want me to tailor it differently or want a Python script or Excel VBA macro instead!