При работе с веб-сайтами часто необходимо извлекать ссылки на изображения для различных целей, например для парсинга веб-страниц, анализа данных или управления контентом. В этой статье блога мы рассмотрим несколько методов получения всех ссылок на изображения с веб-сайта с помощью консоли разработчика Chrome. Каждый метод будет сопровождаться примером кода, который поможет вам понять процесс. Итак, приступим!
Метод 1: запрос к объектной модели документа (DOM)
Пример кода:
// Open the website in Chrome browser
// Open Chrome Developer Console (Ctrl + Shift + J on Windows/Linux or Cmd + Option + J on macOS)
// Switch to the Console tab
// Method to extract image links
function extractImageLinks() {
const images = document.querySelectorAll('img');
const imageLinks = Array.from(images).map((image) => image.src);
return imageLinks;
}
// Call the extractImageLinks function
const allImageLinks = extractImageLinks();
console.log(allImageLinks);
Метод 2: доступ к сетевым запросам
Пример кода:
// Open the website in Chrome browser
// Open Chrome Developer Console (Ctrl + Shift + J on Windows/Linux or Cmd + Option + J on macOS)
// Switch to the Network tab
// Refresh the page to capture network requests
// Filter the requests to view only images
// Look for the image links in the Name or Path column
// Copy the links manually or use the following code to extract them automatically
const imageLinks = [];
const requests = window.performance.getEntriesByType('resource');
requests.forEach((request) => {
if (request.initiatorType === 'img') {
imageLinks.push(request.name);
}
});
console.log(imageLinks);
Метод 3. Использование JavaScript Fetch API
Пример кода:
// Open the website in Chrome browser
// Open Chrome Developer Console (Ctrl + Shift + J on Windows/Linux or Cmd + Option + J on macOS)
// Switch to the Console tab
// Method to extract image links using Fetch API
async function extractImageLinks() {
const response = await fetch(window.location.href);
const html = await response.text();
const parser = new DOMParser();
const doc = parser.parseFromString(html, 'text/html');
const images = doc.querySelectorAll('img');
const imageLinks = Array.from(images).map((image) => image.src);
return imageLinks;
}
// Call the extractImageLinks function
extractImageLinks()
.then((allImageLinks) => console.log(allImageLinks))
.catch((error) => console.error(error));
Метод 4. Использование библиотек или фреймворков JavaScript
Пример кода:
// Open the website in Chrome browser
// Open Chrome Developer Console (Ctrl + Shift + J on Windows/Linux or Cmd + Option + J on macOS)
// Switch to the Console tab
// Method to extract image links using a JavaScript library (jQuery)
function extractImageLinks() {
const images = $('img');
const imageLinks = images.map(function() {
return $(this).attr('src');
}).get();
return imageLinks;
}
// Call the extractImageLinks function
const allImageLinks = extractImageLinks();
console.log(allImageLinks);