Scrapy:如何使用XPath选择div元素中的第一个标记

时间:2017-09-16 00:00:38

标签: python xpath scrapy

我正在使用Scrapy的SitemapSpider从各自的馆藏中提取所有产品链接。我的网站列表都是Shopify商店,链接到产品的代码如下所示:



<div class="grid__item grid-product medium--one-half large--one-third">
  <div class="grid-product__wrapper">
    <div class="grid-product__image-wrapper">
      <a class="grid-product__image-link" href="/collections/accessories/products/black-double-layer-braided-leather-bracelet">
        <img src="//cdn.shopify.com/s/files/1/1150/5108/products/product-image_50ce19b1-c700-4a77-9638-e2ac66a3acef_grande.jpg?v=1457310318" alt="Black Double Layer Braided Leather Bracelet" class="grid-product__image">
          </a>
      
    </div>

    <a href="/collections/accessories/products/black-double-layer-braided-leather-bracelet" class="grid-product__meta">
      <span class="grid-product__title">Black Double Layer Braided Leather Bracelet</span>
      <span class="grid-product__price-wrap">
        <span class="long-dash">—</span>
        <span class="grid-product__price">
          
            $ 15
          
        </span>
      </span>
      
    </a>
  </div>
</div>
&#13;
&#13;
&#13;

显然,两个href都是完全相同的。使用以下代码时,我遇到的问题是抓取两个链接:

product_links = response.xpath('//div//a[contains(@href, "collections") and contains(@href, "products")][1]/@href').extract()

我试图选择同时包含标签作为后代的div元素。从那以后,我只想从第一个标签中拉出href以避免重复链接。

虽然每个网站都是Shopify,但其收藏页面的源代码并不完全相同。所以div元素下的a标签的深度是不一致的,我不能添加像

这样的谓词
//div[@class="grid__item grid-product medium--one-half large--one-third"]

2 个答案:

答案 0 :(得分:0)

product_links = response.xpath('//div//a[contains(@href, "collections") and contains(@href, "products")][1]/@href').extract()
print(product_links[0])  # This is your first a Tag

答案 1 :(得分:0)

只需使用extract_first()命令仅提取第一个匹配的元素。使用它的好处是它避免使用IndexError并在找不到与选择匹配的任何元素时返回None

所以,它应该是:

>>> response.xpath('//div//a[contains(@href, "collections") and contains(@href, "products")]/@href').extract_first()
u'/collections/accessories/products/black-double-layer-braided-leather-bracelet'
相关问题