XPath轴方法 - 捕捉
2021-01-09 本文已影响0人
沫明
XPath轴(XPath Axes)可定义某个相对于当前节点的节点集:
1、child 选取当前节点的所有子元素
2、parent 选取当前节点的父节点
3、descendant 选取当前节点的所有后代元素(子、孙等)
4、ancestor 选取当前节点的所有先辈(父、祖父等)
5、descendant-or-self 选取当前节点的所有后代元素(子、孙等)以及当前节点本身
6、ancestor-or-self 选取当前节点的所有先辈(父、祖父等)以及当前节点本身
7、preceding-sibling 选取当前节点之前的所有同级节点
8、following-sibling 选取当前节点之后的所有同级节点
9、preceding 选取文档中当前节点的开始标签之前的所有节点
10、following 选取文档中当前节点的结束标签之后的所有节点
11、self 选取当前节点
12、attribute 选取当前节点的所有属性
13、namespace 选取当前节点的所有命名空间节点
1. 爬虫xpath遇到的问题:抓取<li>标签,<li>标签下有很多子标签但不想要其中的<a>标签
参考与:https://www.cnpython.com/qa/443194
解决方法:xpath的轴方法--ancestor
res.xpath('//li//text()[not(ancestor::a[@id="main"])]') #剔除id="main"的a标签
res.xpath('//li//text()[not(ancestor::a)]') #剔除所有的a标签
2.xpath 取 当前节点的之后 的所有同级节点(取含有src元素的标签的同级标签)

media_src = resp_news.xpath('//*[@id="contents"]//*[@src]/following-sibling::*/text()')