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. javascript - 数组原声方法中的一段代码2. python小白的基础问题 关于while循环的嵌套3. MySQL客户端吃掉了SQL注解?4. javascript - JS设置Video视频对象的currentTime时出现了问题,IE,Edge,火狐,都可以设置,反而chrom却...5. 求大神帮我看看是哪里写错了 感谢细心解答6. javascript - 百度echarts series数据更新问题7. python - Django分页和查询参数的问题8. javascript - 图片能在网站显示,但控制台仍旧报错403 (Forbidden)9. php自学从哪里开始?10. phpstady在win10上运行
