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. 关于docker下的nginx压力测试2. docker - 各位电脑上有多少个容器啊?容器一多,自己都搞混了,咋办呢?3. docker-compose中volumes的问题4. html - 开发android的调取我web页面 他之前用的是收费的浏览器包 显示是全的换了免费的浏览器包后 显示就不全 是什么原因啊5. 使用 CSS3 的 Media Query 浏览器会加载其他不同分辨率的 css 文件么6. 如何解决Centos下Docker服务启动无响应,且输入docker命令无响应?7. “Webdrivers”可执行文件可能具有错误的权限请参阅https://sites.google.com/a/chromium.org/chromedriver/home8. javascript - 给js写的盒子添加css样式,css样式没起作用。9. 数据挖掘 - 如何用python实现《多社交网络的影响力最大化问题分析》中的算法?10. 前端 - 类到底该如何去命名 .newsList 这种的命名难道真的不是过度语义化吗?~

网公网安备