xpath排除script标签
使用scrapy框架写爬虫的时候,直接爬取request.body的话,会包含<script>标签的代码,如果想排除<script>的标签内容,那么写法如下:
items['body'] = response.xpath('normalize-space(string(/html/body//*[not(self::script)]))')[0].extract()
如果还想排除其他标签:
items['body'] = response.xpath('normalize-space(string(/html/body//*[not(self::script or self::img or self::div)]))')[0].extract()
XPath轴(XPath Axes)可定义某个相对于当前节点的节点集:
- ancestor 选取当前节点的所有先辈(父、祖父等)。
- ancestor-or-self 选取当前节点的所有先辈(父、祖父等)以及当前节点本身。
- attribute 选取当前节点的所有属性。
- child 选取当前节点的所有子元素。
- descendant 选取当前节点的所有后代元素(子、孙等)。
- descendant-or-self 选取当前节点的所有后代元素(子、孙等)以及当前节点本身。
- following 选取文档中当前节点的结束标签之后的所有节点。
- namespace 选取当前节点的所有命名空间节点。
- parent 选取当前节点的父节点。
- preceding 选取文档中当前节点的开始标签之前的所有节点。
- preceding-sibling 选取当前节点之前的所有同级节点。
- self 选取当前节点。
参考链接:
- http://www.w3school.com.cn/xpath/index.asp
- https://stackoverflow.com/questions/38199646/xpath-flatten-text-excluding-certain-nodes
注意:实际过滤结果并没有那么完美!还存在一部分未过滤掉的!
