Python Scrapy选择器问题

时间:2015-03-24 18:54:30

标签: python scrapy scrapy-spider

我正在尝试解析来自名为donedeal.ie的网站的广告信息。将link引导至相关网页。

我收到错误:蜘蛛错误处理http://www.donedeal.ie/find/all/for-sale/ireland>

错误的细节:exceptions.ValueError:无效的XPath:// div [@class =" listing-info"] /

如果我在chrome的控制台中将xpath文本化,它可以正常工作,并且我想要的确切信息在控制台中解析和显示。

任何能够对此有所了解的人都将不胜感激。我为其他网站和xpath尝试了相同的代码,它们似乎有效。

我已经包含完整的跟踪和下面的代码。



2015-03-24 18:47:06+0000 [scrapy] INFO: Scrapy 0.24.5 started (bot: stack)
2015-03-24 18:47:06+0000 [scrapy] INFO: Optional features available: ssl, http11
2015-03-24 18:47:06+0000 [scrapy] INFO: Overridden settings: {'NEWSPIDER_MODULE': 'stack.spiders', 'SPIDER_MODULES': ['stack.spiders'], 'BOT_NAME': 'stack'}
2015-03-24 18:47:07+0000 [scrapy] INFO: Enabled extensions: LogStats, TelnetConsole, CloseSpider, WebService, CoreStats, SpiderState
2015-03-24 18:47:07+0000 [scrapy] INFO: Enabled downloader middlewares: HttpAuthMiddleware, DownloadTimeoutMiddleware, UserAgentMiddleware, RetryMiddleware, DefaultHeadersMiddleware, MetaRefreshMiddleware, HttpCompressionMiddleware, RedirectMiddleware, CookiesMiddleware, ChunkedTransferMiddleware, DownloaderStats
2015-03-24 18:47:07+0000 [scrapy] INFO: Enabled spider middlewares: HttpErrorMiddleware, OffsiteMiddleware, RefererMiddleware, UrlLengthMiddleware, DepthMiddleware
/usr/local/lib/python2.7/dist-packages/scrapy/contrib/pipeline/__init__.py:21: ScrapyDeprecationWarning: ITEM_PIPELINES defined as a list or a set is deprecated, switch to a dict
  category=ScrapyDeprecationWarning, stacklevel=1)
2015-03-24 18:47:07+0000 [scrapy] INFO: Connected to MongoDB mongodb://localhost:27017, using "donedeal/adverts"
2015-03-24 18:47:07+0000 [scrapy] INFO: Enabled item pipelines: MongoDBPipeline
2015-03-24 18:47:07+0000 [stack] INFO: Spider opened
2015-03-24 18:47:07+0000 [stack] INFO: Crawled 0 pages (at 0 pages/min), scraped 0 items (at 0 items/min)
2015-03-24 18:47:07+0000 [scrapy] DEBUG: Telnet console listening on 127.0.0.1:6023
2015-03-24 18:47:07+0000 [scrapy] DEBUG: Web service listening on 127.0.0.1:6080
2015-03-24 18:47:07+0000 [stack] DEBUG: Crawled (200) <GET http://www.donedeal.ie/find/all/for-sale/Ireland/?sort=AGE+DESC&source=ALL&start=0> (referer: None)
2015-03-24 18:47:07+0000 [stack] ERROR: Spider error processing <GET http://www.donedeal.ie/find/all/for-sale/Ireland/?sort=AGE+DESC&source=ALL&start=0>
        Traceback (most recent call last):
          File "/usr/lib/python2.7/dist-packages/twisted/internet/base.py", line 824, in runUntilCurrent
            call.func(*call.args, **call.kw)
          File "/usr/lib/python2.7/dist-packages/twisted/internet/task.py", line 638, in _tick
            taskObj._oneWorkUnit()
          File "/usr/lib/python2.7/dist-packages/twisted/internet/task.py", line 484, in _oneWorkUnit
            result = next(self._iterator)
          File "/usr/local/lib/python2.7/dist-packages/scrapy/utils/defer.py", line 57, in <genexpr>
            work = (callable(elem, *args, **named) for elem in iterable)
        --- <exception caught here> ---
          File "/usr/local/lib/python2.7/dist-packages/scrapy/utils/defer.py", line 96, in iter_errback
            yield next(it)
          File "/usr/local/lib/python2.7/dist-packages/scrapy/contrib/spidermiddleware/offsite.py", line 26, in process_spider_output
            for x in result:
          File "/usr/local/lib/python2.7/dist-packages/scrapy/contrib/spidermiddleware/referer.py", line 22, in <genexpr>
            return (_set_referer(r) for r in result or ())
          File "/usr/local/lib/python2.7/dist-packages/scrapy/contrib/spidermiddleware/urllength.py", line 33, in <genexpr>
            return (r for r in result or () if _filter(r))
          File "/usr/local/lib/python2.7/dist-packages/scrapy/contrib/spidermiddleware/depth.py", line 50, in <genexpr>
            return (r for r in result or () if _filter(r))
          File "/home/fiosta/donedeal/stack/stack/spiders/stack-spider.py", line 15, in parse
            adverts = Selector(response).xpath('//div[@class="listing-info"]/')
          File "/usr/local/lib/python2.7/dist-packages/scrapy/selector/unified.py", line 98, in xpath
            raise ValueError("Invalid XPath: %s" % query)
        exceptions.ValueError: Invalid XPath: //div[@class="listing-info"]/

2015-03-24 18:47:07+0000 [stack] INFO: Closing spider (finished)
2015-03-24 18:47:07+0000 [stack] INFO: Dumping Scrapy stats:
        {'downloader/request_bytes': 273,
         'downloader/request_count': 1,
         'downloader/request_method_count/GET': 1,
         'downloader/response_bytes': 19348,
         'downloader/response_count': 1,
         'downloader/response_status_count/200': 1,
         'finish_reason': 'finished',
         'finish_time': datetime.datetime(2015, 3, 24, 18, 47, 7, 664722),
         'log_count/DEBUG': 3,
         'log_count/ERROR': 1,
         'log_count/INFO': 8,
         'response_received_count': 1,
         'scheduler/dequeued': 1,
         'scheduler/dequeued/memory': 1,
         'scheduler/enqueued': 1,
         'scheduler/enqueued/memory': 1,
         'spider_exceptions/ValueError': 1,
         'start_time': datetime.datetime(2015, 3, 24, 18, 47, 7, 122714)}
2015-03-24 18:47:07+0000 [stack] INFO: Spider closed (finished)
&#13;
&#13;
&#13;

蜘蛛文件(stack-spider.py)

&#13;
&#13;
from scrapy import Spider
from scrapy.selector import Selector

from stack.items import StackItem


class StackSpider(Spider):
    name = "stack"
    allowed_domains = ["donedeal.ie"]
    start_urls = [
        "http://www.donedeal.ie/find/all/for-sale/Ireland/?sort=AGE+DESC&source=ALL&start=0",
    ]

    def parse(self, response):
        adverts = Selector(response).xpath('//div[@class="listing-info"]')

        for advert in adverts:
            item = StackItem()
            item['title'] = advert.xpath(
                'span[@class="county"]/text()').extract()[0]
            item['url'] = advert.xpath(
                'span[@class="multiline-tickets"]/text()').extract()[0]
            yield item
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:1)

选择器中的斜线错误。尝试

xpath('//div[@class="listing-info"]')

另外,当搞乱这些东西时,scrapy shell也很有用。

scrapy shell 'http://www.donedeal.ie/find/all/for-sale/Ireland/?sort=AGE+DESC&source=ALL&start=0'