我试图从一个网站获得一些数据,但当我使用下面的代码时,它返回所有匹配的元素,我只想返回第一个匹配!我已经试过了,但没有回音!你知道吗
# -*- coding: utf-8 -*-
import scrapy
from gumtree.items import GumtreeItem
class FlatSpider(scrapy.Spider):
name = "flat"
allowed_domains = ["gumtree.com"]
start_urls = (
'https://www.gumtree.com/flats-for-sale',
)
def parse(self, response):
item = GumtreeItem()
item['title'] = response.xpath('//*[@class="listing-title"][1]/text()').extract()
return item
如何使用xpath选择器只选择一个元素?你知道吗
严格地说应该是
response.xpath('(//*[@class="listing-title"])[1]/text()')
,但是如果您想要获取每个广告的标题(例如创建一个项目),您可能应该这样做:这是因为第一个元素实际上是空的-只过滤掉非空值并使用
extract_first()
-对我有效:相关问题 更多 >
编程相关推荐