javascript - 爬取網頁Jquery選擇器first-child的問題
問題描述
在爬取一個網站的時候,感覺h2 和 h3 是一樣的結構,為什么 h2:first-child 可以取到數據, h3就不行。
最終的結果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,所以為空
相關文章:
1. java - new + 類名,一定需要申明一個對象嗎?2. javascript - 前端開發 本地靜態文件頻繁修改,預覽時的緩存怎么解決?3. java - public <T> T findOne(T record) 這是什么意思4. android - 優酷的安卓及蘋果app還在使用flash技術嗎?5. docker不顯示端口映射呢?6. 新手 - Python 爬蟲 問題 求助7. mysql數據庫每次查詢是一條線程嗎?8. python - linux怎么在每天的凌晨2點執行一次這個log.py文件9. 如何分別在Windows下用Winform項模板+C#,在MacOSX下用Cocos Application項目模板+Objective-C實現一個制作游戲的空的黑窗口?10. 小程序怎么加外鏈,語句怎么寫!求救新手,開文檔沒發現
