我正在抓取此页面以获取每个广告的数据: http://www.cars2buy.co.uk/business-car-leasing/Abarth/695C/ ?
每个广告都在一个叫content的类中,所以我写了一个for循环来获取所有内容类,然后拼命获取每个内容“Ad”的数据,但是我在每次循环迭代中都获取了所有内容的数据。这是我在 scrapy shell 中的代码:
scrapy shell "http://www.cars2buy.co.uk/business-car-leasing/Abarth/695C/"
for content in response.xpath('//*[@class="pitem"]/div[1]/div[2]/div[1]'):
print content.xpath('//*[@class="detail"]/p/text()[2]').extract()
但是输出是:
[u' 48 months', u' 48 months', u' 48 months', u' 36 months', u' 48 months', u' 48 months', u' 48 months', u' 48 months', u' 48 months', u' 36 months']
[u' 48 months', u' 48 months', u' 48 months', u' 36 months', u' 48 months', u' 48 months', u' 48 months', u' 48 months', u' 48 months', u' 36 months']
[u' 48 months', u' 48 months', u' 48 months', u' 36 months', u' 48 months', u' 48 months', u' 48 months', u' 48 months', u' 48 months', u' 36 months']
[u' 48 months', u' 48 months', u' 48 months', u' 36 months', u' 48 months', u' 48 months', u' 48 months', u' 48 months', u' 48 months', u' 36 months']
[u' 48 months', u' 48 months', u' 48 months', u' 36 months', u' 48 months', u' 48 months', u' 48 months', u' 48 months', u' 48 months', u' 36 months']
[u' 48 months', u' 48 months', u' 48 months', u' 36 months', u' 48 months', u' 48 months', u' 48 months', u' 48 months', u' 48 months', u' 36 months']
[u' 48 months', u' 48 months', u' 48 months', u' 36 months', u' 48 months', u' 48 months', u' 48 months', u' 48 months', u' 48 months', u' 36 months']
[u' 48 months', u' 48 months', u' 48 months', u' 36 months', u' 48 months', u' 48 months', u' 48 months', u' 48 months', u' 48 months', u' 36 months']
[u' 48 months', u' 48 months', u' 48 months', u' 36 months', u' 48 months', u' 48 months', u' 48 months', u' 48 months', u' 48 months', u' 36 months']
[u' 48 months', u' 48 months', u' 48 months', u' 36 months', u' 48 months', u' 48 months', u' 48 months', u' 48 months', u' 48 months', u' 36 months']
这意味着它在每次迭代中获取所有标签的数据!! 我需要的输出是:
48 months 48 months 48 months 36 months 48 months 48 months 48 months 48 months 48 months 36 months
最佳答案
为了获取每个广告的数据,您可以使用以下代码:
def parse(self, response):
for detail in response.xpath('//div[@class="detail"]/p'):
item = dict()
item['term'] = detail.xpath('text()[2]').extract_first()
item['mileage'] = detail.xpath('text()[4]').extract_first()
item['payment'] = detail.xpath('text()[6]').extract_first()
item['fee'] = detail.xpath('text()[8]').extract_first()
yield item
# {'term': ' 48 months', 'mileage': ' 10,000', 'payment': ' £2,227.86 + VAT', 'fee': ' £249.00 + VAT'}
请注意,您需要使用 extract_first()
方法,因为 extract()
返回一个列表。
关于python - 如何获取每个标签的数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43690900/