スプレッドシートにURLを記述すると<title>タグ、デスクリプション、カノニカルを取得する下記のコードをGASで作成したのですが、
途中で存在しないURLが入っているとその列の<title>タグ等の入力をスキップし、そのままその後のURLの値が入ってしまうため最終的に1列ズレてしまいます。
存在しないURLまたは間違っているURLを入力した際にスキップではなくその列に「エラー」等の文字列を入力し、ズレが起きないようにしたいのですが
もしその方法がわかる方がいらっしゃいましたらご助力お願いしたいです。よろしくお願いいたします。
1function TDextract(){ 2 const sheet = SpreadsheetApp.getActiveSheet(), 3 startRow = 2, 4 startCol = 6, 5 URLListRow = startRow - 1, 6 7 metaInfo = [ 8 { 9 outName:'desc', 10 name:'name', 11 prop:'description', 12 } 13 ] 14 15 16 /* 17 ======================================== 18 以下 script 19 ======================================== 20 */ 21 22 // clear cell 23 for (let i = startRow; i <= sheet.getLastColumn(); i++){ 24 const dataRange = sheet.getRange(startCol,i,sheet.getLastRow()); 25 dataRange.clearContent(); 26 } 27 28 // create url data 29 const urlData = sheet.getRange(startCol,URLListRow,sheet.getLastRow() - 1).getValues(); 30 let ary = ''; 31 for (var a = 0; a<urlData.length;a++){ 32 if(urlData[a][0]){ 33 ary = ary + String(urlData[a][0]) + ',' 34 } 35 } 36 ary = ary.split(','); 37 ary.pop(); 38 39 40 // header option 41 const options = { 42 method: "GET", 43 "muteHttpExceptions" : true, 44 "validateHttpsCertificates" : false, 45 "followRedirects" : false 46 } 47 let result = []; 48 49 // get html data 50 for(var i = 0; i < ary.length; i++){ 51 try { 52 let obj = Object.assign({}); 53 let r = Object.assign({}); 54 let resultURL = ary[i]; 55 const res = UrlFetchApp.fetch(resultURL,options); 56 const content = res.getContentText() 57 const $ = Cheerio.load(content); 58 obj.title = $('title').text(); 59 metaInfo.forEach((v)=>{ 60 const reg = new RegExp(v.prop,'g'); 61 if(content.match(reg)){ 62 obj[v.outName] = $(`meta[${v.name}="${v.prop}"]`).attr("content"); 63 }else{ 64 obj[v.outName] = false; 65 } 66 }) 67 obj.canonical = $('link[rel="canonical"]').attr('href'); 68 69 r.props = Object.assign({},obj); 70 71 result.push(r); 72 73 obj = null; 74 r = null; 75 Utilities.sleep(1000); 76 } catch(e) { 77 console.log('Error:'+e); 78 } 79 } 80 81 // draw cell 82 result.forEach((d,r)=>{ 83 Object.keys(d.props).forEach((k,i)=>{ 84 const row = startCol + r; 85 const col = startRow + i; 86 sheet.getRange(row, col).setValue(d.props[k]); 87 }) 88 }) 89}

回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2022/04/11 00:37