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. python如何搜索字符串2. java - app或者微信也公用这套后端代码可以吗?还是重写一套后端代码呢?3. python3.x - 我把3.6的卸载了,也重启了,但是在cmd用python -V指令查看版本时,还是提示下图的python3.64. 一个走错路的23岁傻小子的提问5. python - 在 flask-sqlalchemy中,如何将查询语句转换成原始SQL打印出来?6. python3文本中超链接处理问题求助7. python 多进程 或者 多线程下如何高效的同步数据?8. python读取一个文档中的内容并提取处理9. 网页爬虫 - python+requests 网页重定向求解10. python - 假定有json数据多条记录,如何根据KEY的值返回一条记录?