前幾天波哥分享了一個Chrome Console 抓取網頁信息和圖片URL, 這個程式碼較為簡單,針對性的處理一些較簡單的圖片和URL抓取需求,但是,這個程式碼有個問題就是需要在Chrome Console的控制中臺去手動複製匯出的記錄。很是麻煩,但是javascript是不支援直接儲存日誌檔案文件的,所以只能利用瀏覽器本身的API來下載了。
所以今天波哥要分享的程式碼是一個進階版,可以遍歷所有指定的CSS Selector然後點選對應的圖片,待文字顯示出來後再抓取,由於載入圖片可能會有一定的延時,所以特地加了一個延時的程式碼。
所有元素抓取完畢後,會保存為log.txt。
(async () => { // 獲取所有的 TemplateItem 元素 const templateItems = document.querySelectorAll('.Templates-module--TemplateItem--0VNo4'); // 建立一個字元串來儲存結果 let logContent = ''; // 定義延時等待函數 function delay(ms) { return new Promise((resolve) => setTimeout(resolve, ms)); } // 遍歷每個 TemplateItem 元素 for (const item of templateItems) { // 獲取圖片連結 const imageUrl = item.style.backgroundImage.match(/\((.*?)\)/)[1].replace(/('|")/g, ''); // 點選 TemplateItem 元素 item.click(); // 等待一段時間,讓文案顯示出來 await delay(1000); // 調整延時的時間,根據實際情況進行調整 // 獲取對應的文案 const textArea = document.querySelector('.c-textarea__input'); const textContent = textArea.value; // 將結果新增到字元串中 logContent += '圖片:' + imageUrl + '\n'; logContent += '文案:' + textContent + '\n\n'; } // 將結果儲存到檔案(通過下載方式) const fileName = 'log.txt'; downloadLog(logContent, fileName); // 使用上述下載函數進行檔案下載 // 下載函數 function downloadLog(logContent, fileName) { const element = document.createElement('a'); element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(logContent)); element.setAttribute('download', fileName); element.style.display = 'none'; document.body.appendChild(element); element.click(); document.body.removeChild(element); } })();
猜你喜歡
轉載請保留原文連結:https://www.booooker.com/1299.html
- 本站所有文章,如無特殊說明或標註,均為本站原創釋出。在未徵得本站同意時,禁止複製、盜用、採集、釋出本站內容。
- 本站資源僅供研究、學習交流之用,若使用商業用途,請購買正版授權,否則產生的一切後果將由下載使用者自行承擔。
- 如若本站內容侵犯了原著者的合法權益,可聯絡我們進行處理。 聯絡方式(#替換成@):info#booooker.com
評論(0)