Tom Brereton Tom Brereton - 3 months ago 17
Python Question

XPath expression not working in scrapy spider but it is scrapy shell

I'm working on a small project to get my head around scrapy and I've come across a problem with my xpath.

The xpath works in the scrapy shell and the equivalent in javascript but when I put it in the spider.py file it doesn't work. Do I need to change some of the xpath in the spider.py file?

I run the following the the scrapy shell.

scrapy shell -s USER_AGENT='Safari/537.36' 'https://www.gumtree.com/search?q=iphone+6'

response.xpath('//div[@class="listing-content"]//meta[@itemprop="price"]/@content').extract()


Which correctly returns the prices. But when I put it in the spider.py file it returns nothing. The spider.py is the following:

import scrapy

from phone_scraper.items import PhoneScraperItem


class PhoneSpider(scrapy.Spider):

"""Docstring for PhoneSpider. """

name = "phone"
allowed_domains = ["gumtree.com"]
start_urls = [
"https://www.gumtree.com/search?q=iphone+6"
]

def parse(self, response):
item = PhoneScraperItem()
item['price'] = response.xpath('//div[@class="listing-content"]//meta[@itemprop="price"]/@content').extract()


I then run it with the following in the terminal:

scrapy crawl phone -o items.json


To get this output in the console:

2016-08-16 23:44:35 [scrapy] INFO: Scrapy 1.1.1 started (bot: phone_scraper)
2016-08-16 23:44:35 [scrapy] INFO: Overridden settings: {'NEWSPIDER_MODULE': 'phone_scraper.spiders', 'FEED_URI': 'items.json', 'SPIDER_MODULES': ['phone_scraper.spiders'], 'BOT_NAME': 'phone_scraper', 'USER_AGENT': 'Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.93 Safari/537.36', 'FEED_FORMAT': 'json'}
2016-08-16 23:44:35 [scrapy] INFO: Enabled extensions:
['scrapy.extensions.feedexport.FeedExporter',
'scrapy.extensions.logstats.LogStats',
'scrapy.extensions.telnet.TelnetConsole',
'scrapy.extensions.corestats.CoreStats']
2016-08-16 23:44:35 [scrapy] INFO: Enabled downloader middlewares:
['scrapy.downloadermiddlewares.httpauth.HttpAuthMiddleware',
'scrapy.downloadermiddlewares.downloadtimeout.DownloadTimeoutMiddleware',
'scrapy.downloadermiddlewares.useragent.UserAgentMiddleware',
'scrapy.downloadermiddlewares.retry.RetryMiddleware',
'scrapy.downloadermiddlewares.defaultheaders.DefaultHeadersMiddleware',
'scrapy.downloadermiddlewares.redirect.MetaRefreshMiddleware',
'scrapy.downloadermiddlewares.httpcompression.HttpCompressionMiddleware',
'scrapy.downloadermiddlewares.redirect.RedirectMiddleware',
'scrapy.downloadermiddlewares.cookies.CookiesMiddleware',
'scrapy.downloadermiddlewares.chunked.ChunkedTransferMiddleware',
'scrapy.downloadermiddlewares.stats.DownloaderStats']
2016-08-16 23:44:35 [scrapy] INFO: Enabled spider middlewares:
['scrapy.spidermiddlewares.httperror.HttpErrorMiddleware',
'scrapy.spidermiddlewares.offsite.OffsiteMiddleware',
'scrapy.spidermiddlewares.referer.RefererMiddleware',
'scrapy.spidermiddlewares.urllength.UrlLengthMiddleware',
'scrapy.spidermiddlewares.depth.DepthMiddleware']
2016-08-16 23:44:35 [scrapy] INFO: Enabled item pipelines:
[]
2016-08-16 23:44:35 [scrapy] INFO: Spider opened
2016-08-16 23:44:35 [scrapy] INFO: Crawled 0 pages (at 0 pages/min), scraped 0 items (at 0 items/min)
2016-08-16 23:44:35 [scrapy] DEBUG: Telnet console listening on 127.0.0.1:6024
2016-08-16 23:44:35 [scrapy] DEBUG: Crawled (200) <GET https://www.gumtree.com/search?q=iphone+6> (referer: None)
2016-08-16 23:44:35 [scrapy] INFO: Closing spider (finished)
2016-08-16 23:44:35 [scrapy] INFO: Dumping Scrapy stats:
{'downloader/request_bytes': 305,
'downloader/request_count': 1,
'downloader/request_method_count/GET': 1,
'downloader/response_bytes': 51936,
'downloader/response_count': 1,
'downloader/response_status_count/200': 1,
'finish_reason': 'finished',
'finish_time': datetime.datetime(2016, 8, 16, 22, 44, 35, 887734),
'log_count/DEBUG': 2,
'log_count/INFO': 7,
'response_received_count': 1,
'scheduler/dequeued': 1,
'scheduler/dequeued/memory': 1,
'scheduler/enqueued': 1,
'scheduler/enqueued/memory': 1,
'start_time': datetime.datetime(2016, 8, 16, 22, 44, 35, 407480)}
2016-08-16 23:44:35 [scrapy] INFO: Spider closed (finished)





EDIT: Follow-up-question

I have a follow up question using a do loop to get the above information. I hope this is the right way to ask it.

I have changed the parse function from above to the following and now it is not returning anything again.

def parse(self, response):
for sel in response.xpath('//div[@class="listing-content"]'):
item = PhoneScraperItem()
item['price'] = sel.xpath('meta[@item-prop="price"]/@content').extract()
yield item


Am I concatenating the XPath incorrectly?

Answer

You forgot to return the item from the parse() callback:

def parse(self, response):
    item = PhoneScraperItem()
    item['price'] = response.xpath('//div[@class="listing-content"]//meta[@itemprop="price"]/@content').extract()
    return item