javascript - 爬取網(wǎng)頁Jquery選擇器first-child的問題
問題描述
在爬取一個網(wǎng)站的時候,感覺h2 和 h3 是一樣的結(jié)構(gòu),為什么 h2:first-child 可以取到數(shù)據(jù), h3就不行。
最終的結(jié)果h2_1和h2_2是一樣的,沒問題。h3_1是ok的,h3_2是空,請問這是為什么?
代碼如下,
const jsdom = require(’jsdom’);const jquery = require(’jquery’);jsdom.env(’https://www.osram.com/os/news-and-events/spotlights/index.jsp’, [], { defaultEncoding: ’utf-8’}, function(err, window) { if(err) {console.error(’error get news url from page [%s]’);return; } let $ = jquery(window); let el = $(’p.col-xs-6.col-sm-7.colalign:first’); let h2_1 = $(el).find(’h2.font-headline-teaser’).text(); console.log(’h2_1=’ + h2_1); let h2_2 = $(el).find(’h2.font-headline-teaser:first-child’).text(); console.log(’h2_2=’ + h2_2); let h3_1 = $(el).find(’h3.font-sub-headline’).text(); console.log(’h3_1=’ + h3_1); let h3_2 = $(el).find(’h3.font-sub-headline:first-child’).text(); console.log(’h3_2=’ + h3_2); window.close();});
問題解答
回答1:選擇器xxx:first-child是指,xxx的父元素的第一個子元素為xxx時,選中xxx,需要同時滿足這兩個條件。
不是xxx父元素的第一個子元素,也不是xxx的父元素的子元素中第一個xxx
h2.font-headline-teaser的父元素的第一個子元素為h2.font-headline-teaser,所以能選中
h3.font-sub-headline的父元素的第一個子元素不是h3.font-sub-headline,所以為空
相關(guān)文章:
1. javascript - 微信網(wǎng)頁開發(fā)從菜單進入頁面后,按返回鍵沒有關(guān)閉瀏覽器而是刷新當(dāng)前頁面,求解決?2. 求救一下,用新版的phpstudy,數(shù)據(jù)庫過段時間會消失是什么情況?3. mysql replace 死鎖4. mysql - C#連接數(shù)據(jù)庫時一直這一句出問題int i = cmd.ExecuteNonQuery();5. python - 數(shù)據(jù)與循環(huán)次數(shù)對應(yīng)不上6. extra沒有加載出來7. android - 安卓做前端,PHP做后臺服務(wù)器 有什么需要注意的?8. 環(huán)境搭建 - anaconda 創(chuàng)建python2.7環(huán)境中打開編譯器確是3.6版本9. php傳對應(yīng)的id值為什么傳不了啊有木有大神會的看我下方截圖10. mysql - ubuntu開啟3306端口失敗,有什么辦法可以解決?
