javascript - 爬取網(wǎng)頁Jquery選擇器first-child的問題
問題描述
在爬取一個(gè)網(wǎng)站的時(shí)候,感覺h2 和 h3 是一樣的結(jié)構(gòu),為什么 h2:first-child 可以取到數(shù)據(jù), h3就不行。
最終的結(jié)果h2_1和h2_2是一樣的,沒問題。h3_1是ok的,h3_2是空,請(qǐng)問這是為什么?
代碼如下,
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的父元素的第一個(gè)子元素為xxx時(shí),選中xxx,需要同時(shí)滿足這兩個(gè)條件。
不是xxx父元素的第一個(gè)子元素,也不是xxx的父元素的子元素中第一個(gè)xxx
h2.font-headline-teaser的父元素的第一個(gè)子元素為h2.font-headline-teaser,所以能選中
h3.font-sub-headline的父元素的第一個(gè)子元素不是h3.font-sub-headline,所以為空
相關(guān)文章:
1. 在應(yīng)用配置文件 app.php 中找不到’route_check_cache’配置項(xiàng)2. html按鍵開關(guān)如何提交我想需要的值到數(shù)據(jù)庫3. HTML 5輸入框只能輸入漢字、字母、數(shù)字、標(biāo)點(diǎn)符號(hào)?正則如何寫?4. javascript - 請(qǐng)教如何獲取百度貼吧新增的兩個(gè)加密參數(shù)5. gvim - 誰有vim里CSS的Indent文件, 能縮進(jìn)@media里面的6. 跟著課件一模一樣的操作使用tp6,出現(xiàn)了錯(cuò)誤7. PHP類屬性聲明?8. javascript - 求助canvas繪制馬賽克的問題,老是取色不準(zhǔn)9. java - 安卓接入微信登錄,onCreate不會(huì)執(zhí)行10. python沒入門,請(qǐng)教一個(gè)問題
