如何使用xpath获取所有<img/>代码,但在<div>下排除{foot}的内容为<img/>标记?</div>

时间:2013-10-03 08:43:17

标签: html xpath web-scraping

你们知道我怎样才能获得所有img标签但是在使用xpath的id为footer的div下排除img标签?

目前要在html页面上获取所有img标签,我这样做: imgs = tree.xpath('//img')

但我想在id为footer的div下排除所有img标签,所以我正在做这个:

imgs = tree.xpath('//*[not(div[@id="footer"])]//img')&lt; - 但这不起作用

1 个答案:

答案 0 :(得分:6)

应该是这样的:

imgs = tree.xpath('//img[not(parent::div[@id="footer"])]')

故障:

  • //img - 搜索所有<img>代码
  • [] - where where
  • not(parent::div[@id="footer"]) - 没有(带有)值为footer
  • 的属性ID的(直接)父div

如果<div>元素不是<img>的直接父级,而是其中一个父级,请使用:

imgs = tree.xpath('//img[not(ancestor::div[@id="footer"])]')
相关问题