Scrapy:如何使用XPath选择div元素中的第一个标记
问题描述:
我正在使用Scrapy的SitemapSpider从各自的集合中提取所有产品链接。我的网站的名单都是Shopify商店,并链接到该产品的代码如下所示:Scrapy:如何使用XPath选择div元素中的第一个标记
<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>
很显然,无论是HREF的是完全一样的。我在使用下面的代码时,刮两条链路的问题:
product_links = response.xpath('//div//a[contains(@href, "collections") and contains(@href, "products")][1]/@href').extract()
我想选择一种既具有标签作为后代的div元素。从那以后,我只想从第一个标签中提取href以避免重复的链接。
虽然每个网站都是Shopify,但其集合页面的源代码并不完全相同。所以div元素下的一个标签的深浅不一致,我不能添加一个谓词像
//div[@class="grid__item grid-product medium--one-half large--one-third"]
答
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
+0
这不起作用。使用Scrapy的SitemapSpider时,response.xpath()将返回它从站点地图中刮取的每个页面的列表。 print(product_links [0])返回每个列表的第一个项目,所以我只会从每个集合中挖出第一个产品 – barnesc
答
只需使用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'
我做了一个全新的职位,阐明了我在问什么,并给出了代码的更加简化。如果其他人有类似的问题,我宁愿不删除这个问题。 [链接到改进的问题](https://*.com/questions/46258500/xpath-and-scrapy-scraping-links-when-the-depth-and-quantity-of-a-tags-are-inco) – barnesc