用Javascript抓取網頁內容

打印網頁所有h2的內容

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
Array.from(document.querySelectorAll('h2')).map(x => console.log(x.textContent))
Array.from(document.querySelectorAll('h2')).map(x => console.log(x.textContent))
Array.from(document.querySelectorAll('h2')).map(x => console.log(x.textContent))

document.querySelectorAll
document.querySelectorAll返回類型為
NodeList
NodeList
NodeList
NodeList是不能用map方法的。所以需要用
Array.from
Array.from先把
NodeList
NodeList轉換成
array
array,就可以用map對每個元素操作了。

querySelectorAll
querySelectorAll的參數和CSS一樣

querySelectorAll
querySelectorAll的輸入
選中DOM例子
h2select by tag <h2> </h2>
.cls1.cls2.cls3select by class name <h2 class=”cls1 cls2 cls3″></h2>
#id1select by id <h2 id=”id1″></h2>

除了用也可以用

document.querySelectorAll
document.querySelectorAll也可以用document.getElementsByTagName達到一樣效果。

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
Array.from(document.getElementsByTagName('h2')).map(x => console.log(x.textContent))
Array.from(document.getElementsByTagName('h2')).map(x => console.log(x.textContent))
Array.from(document.getElementsByTagName('h2')).map(x => console.log(x.textContent))

Leave a Comment

Your email address will not be published.