【问题标题】:how to get nested scrapy - selectors如何获得嵌套的scrapy - 选择器
【发布时间】:2020-08-16 17:30:32
【问题描述】:

如何获取以下html的'img src'的xpath

<a class=product-tile">
 <img src="image-file-here">
</a>

【问题讨论】:

  • 你真的需要 xpath 吗?在这里使用 CSS 选择器会更容易/更通用......你想要img 元素还是img 的实际src 属性?
  • 我需要图片的实际src属性

标签: python-3.x scrapy


【解决方案1】:

听起来您想提取 src 属性的值,如果是这样,这应该可以解决问题:

response.xpath('//a[@class="product-tile"]/img/@src').get()

Scrapy docs on selectors

【讨论】:

    【解决方案2】:

    您可以使用更简单的 CSS 选择器并在底层转换为 XPATH。

    试试这个

    response.css('.product-tile ::attr(src)').get()
    

    【讨论】:

    • 我可能会选择:a.product-tile &gt; img::attr(src)
    • 我们通常在编写选择器时避免使用 HTML 标签,因为它们更容易发生变化和不一致。
    【解决方案3】:

    如果您正在寻找 XPTH,您可以在这里使用 extract_first() 获取图像源以进行首次查找

    response.xpath('//img/@src').extract_first()
    

    如果你有复杂的 html,你可以使用更具体的 xpath

    response.xpath('//a[@class="product-tile"]/@src').extract_first()
    

    如果您要提取多个图像 src 链接,请使用 extract()

    response.xpath('//a[@class="product-tile"]/@src').extract()
    

    这样的标签内可能有多个 src 链接

    <a class=product-tile">
     <img src="image-file-here">
     <a>
      <img src="image-file-here">
     </a>
     <img src="image-file-here">
     <img src="image-file-here">
    </a>

    所以在@src之前使用//

    response.xpath('//a[@class="product-tile"]//@src').extract()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-10-17
      • 2019-02-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-30
      相关资源
      最近更新 更多