来自Scrapy的CSV和JSON的空输出文件

时间:2017-04-15 21:22:45

标签: python json csv scrapy scrapy-spider

所以我一直在为我的学校做这个项目,我遇到了这个问题,结果文件中没有输出。我试图找到它的解决方案。他们似乎都不适合我。

这是我的Scrapy蜘蛛代码:

from scrapy.contrib.linkextractors import LinkExtractor
from scrapy.contrib.linkextractors.lxmlhtml import LxmlLinkExtractor
from scrapy.contrib.spiders import Rule, CrawlSpider
from scrapy.selector import Selector
from scrapy_craigslist.items import ScrapyCraigslistItem


class MySpider(CrawlSpider):
    name = 'craigslist'
    allowed_domains = ['vancouver.craigslist.ca']
    start_urls = ['https://vancouver.craigslist.ca/search/apa?']
    rules = (
        Rule(LxmlLinkExtractor(
            allow=(r'vancouver.craigslist.ca/search/apa.*'),
            deny = (r'.*format\=rss.*')
        ),
            callback="parse_items_1",
            follow= False,
             ),
        )

    def parse_items_1(self, response):
        self.logger.info('You are now crawling: %s', response.url)
        items = []
        hxs = Selector(response)
        contents = hxs.xpath("//div[@class='rows']/*")
        for content in contents:
            item = ScrapyCraigslistItem()
            item ["title"] = content.xpath("//p/span/span/a/span/text()").extract()[0]
            k = content.xpath("//p/a/@href").extract()[0]
            item ['ad_url'] = 'https://vancouver.craigslist.ca{}'.format(''.join(k))
            item ["post_date"] = content.xpath("//p/span/span/time/text()").extract()[0]
            item ["post_date_specific"] = content.xpath("//p/span/span/time/@datetime").extract()[0]
            item ["price"] = content.xpath("//p/span/span[@class='l2']/span/text()").extract()[0]
            item ["location"] = content.xpath("//p/span/span[@class='l2']/span[@class='pnr']/small/text()").extract()[0].strip()
            return item

我的items.py脚本是:

import scrapy


class ScrapyCraigslistItem(scrapy.Item):
    title = scrapy.Field()
    post_date = scrapy.Field()
    post_date_specific = scrapy.Field()
    price = scrapy.Field()
    location = scrapy.Field()
    ad_url = scrapy.Field()

我的pipelines.py脚本是:

from scrapy.exceptions import DropItem

class DuplicatesPipeline(object):

    def __init__(self):
        self.titles_seen = set()

    def process_item(self, item, spider):
        if item['title'] in self.titles_seen:
            raise DropItem("Duplicate item found: %s" % item)
        else:
            self.titles_seen.add(item['title'])
            return item

我的settings.py是:

BOT_NAME = 'scrapy_craigslist'

SPIDER_MODULES = ['scrapy_craigslist.spiders']
NEWSPIDER_MODULE = 'scrapy_craigslist.spiders'

ITEM_PIPELINES = {
    'scrapy_craigslist.pipelines.DuplicatesPipeline': 10,

}

USER_AGENT = "Mozilla/5.0 (Windows NT 5.1; rv:12.2.1) Gecko/20120616 Firefox/12.2.1 PaleMoon/12.2.1"

最后,这是我在命令行中获得JSON和CSV

的结果
/home/logan/Desktop/scrapy-craigslist-master/scrapy_craigslist/spiders/craigslist_scrapy.py:1: ScrapyDeprecationWarning: Module `scrapy.contrib.linkextractors` is deprecated, use `scrapy.linkextractors` instead
  from scrapy.contrib.linkextractors import LinkExtractor
/home/logan/Desktop/scrapy-craigslist-master/scrapy_craigslist/spiders/craigslist_scrapy.py:2: ScrapyDeprecationWarning: Module `scrapy.contrib.linkextractors.lxmlhtml` is deprecated, use `scrapy.linkextractors.lxmlhtml` instead
  from scrapy.contrib.linkextractors.lxmlhtml import LxmlLinkExtractor
/home/logan/Desktop/scrapy-craigslist-master/scrapy_craigslist/spiders/craigslist_scrapy.py:3: ScrapyDeprecationWarning: Module `scrapy.contrib.spiders` is deprecated, use `scrapy.spiders` instead
  from scrapy.contrib.spiders import Rule, CrawlSpider
2017-04-15 14:12:44 [scrapy.utils.log] INFO: Scrapy 1.3.3 started (bot: scrapy_craigslist)
2017-04-15 14:12:44 [scrapy.utils.log] INFO: Overridden settings: {'NEWSPIDER_MODULE': 'scrapy_craigslist.spiders', 'FEED_URI': 'load.csv', 'SPIDER_MODULES': ['scrapy_craigslist.spiders'], 'BOT_NAME': 'scrapy_craigslist', 'USER_AGENT': 'Mozilla/5.0 (Windows NT 5.1; rv:12.2.1) Gecko/20120616 Firefox/12.2.1 PaleMoon/12.2.1', 'FEED_FORMAT': 'csv'}
2017-04-15 14:12:44 [scrapy.middleware] INFO: Enabled extensions:
['scrapy.extensions.feedexport.FeedExporter',
 'scrapy.extensions.logstats.LogStats',
 'scrapy.extensions.telnet.TelnetConsole',
 'scrapy.extensions.corestats.CoreStats']
2017-04-15 14:12:44 [scrapy.middleware] INFO: Enabled downloader middlewares:
['scrapy.downloadermiddlewares.httpauth.HttpAuthMiddleware',
 'scrapy.downloadermiddlewares.downloadtimeout.DownloadTimeoutMiddleware',
 'scrapy.downloadermiddlewares.defaultheaders.DefaultHeadersMiddleware',
 'scrapy.downloadermiddlewares.useragent.UserAgentMiddleware',
 'scrapy.downloadermiddlewares.retry.RetryMiddleware',
 'scrapy.downloadermiddlewares.redirect.MetaRefreshMiddleware',
 'scrapy.downloadermiddlewares.httpcompression.HttpCompressionMiddleware',
 'scrapy.downloadermiddlewares.redirect.RedirectMiddleware',
 'scrapy.downloadermiddlewares.cookies.CookiesMiddleware',
 'scrapy.downloadermiddlewares.stats.DownloaderStats']
2017-04-15 14:12:44 [scrapy.middleware] INFO: Enabled spider middlewares:
['scrapy.spidermiddlewares.httperror.HttpErrorMiddleware',
 'scrapy.spidermiddlewares.offsite.OffsiteMiddleware',
 'scrapy.spidermiddlewares.referer.RefererMiddleware',
 'scrapy.spidermiddlewares.urllength.UrlLengthMiddleware',
 'scrapy.spidermiddlewares.depth.DepthMiddleware']
2017-04-15 14:12:44 [scrapy.middleware] INFO: Enabled item pipelines:
['scrapy_craigslist.pipelines.DuplicatesPipeline']
2017-04-15 14:12:44 [scrapy.core.engine] INFO: Spider opened
2017-04-15 14:12:44 [scrapy.extensions.logstats] INFO: Crawled 0 pages (at 0 pages/min), scraped 0 items (at 0 items/min)
2017-04-15 14:12:44 [scrapy.extensions.telnet] DEBUG: Telnet console listening on 127.0.0.1:6023
2017-04-15 14:12:45 [scrapy.core.engine] DEBUG: Crawled (200) <GET https://vancouver.craigslist.ca/search/apa> (referer: None)
2017-04-15 14:12:45 [scrapy.core.engine] DEBUG: Crawled (200) <GET https://vancouver.craigslist.ca/search/apa> (referer: https://vancouver.craigslist.ca/search/apa)
2017-04-15 14:12:46 [craigslist] INFO: You are now crawling: https://vancouver.craigslist.ca/search/apa
2017-04-15 14:12:46 [scrapy.downloadermiddlewares.redirect] DEBUG: Redirecting (302) to <GET https://vancouver.craigslist.ca/search/apa?sale_date=2017-04-15&sort=upcoming> from <GET https://vancouver.craigslist.ca/search/apa?sort=upcoming>
2017-04-15 14:12:46 [scrapy.core.engine] DEBUG: Crawled (200) <GET https://vancouver.craigslist.ca/search/apa?sort=priceasc> (referer: https://vancouver.craigslist.ca/search/apa)
2017-04-15 14:12:46 [scrapy.core.engine] DEBUG: Crawled (200) <GET https://vancouver.craigslist.ca/search/apa?s=120> (referer: https://vancouver.craigslist.ca/search/apa)
2017-04-15 14:12:46 [craigslist] INFO: You are now crawling: https://vancouver.craigslist.ca/search/apa?sort=priceasc
2017-04-15 14:12:46 [craigslist] INFO: You are now crawling: https://vancouver.craigslist.ca/search/apa?s=120
2017-04-15 14:12:46 [scrapy.core.engine] DEBUG: Crawled (200) <GET https://vancouver.craigslist.ca/search/apa?sale_date=2017-04-15&sort=upcoming> (referer: https://vancouver.craigslist.ca/search/apa)
2017-04-15 14:12:46 [scrapy.core.engine] DEBUG: Crawled (200) <GET https://vancouver.craigslist.ca/search/apa?sort=date> (referer: https://vancouver.craigslist.ca/search/apa)
2017-04-15 14:12:46 [scrapy.core.engine] DEBUG: Crawled (200) <GET https://vancouver.craigslist.ca/search/apa?sort=pricedsc> (referer: https://vancouver.craigslist.ca/search/apa)
2017-04-15 14:12:46 [craigslist] INFO: You are now crawling: https://vancouver.craigslist.ca/search/apa?sale_date=2017-04-15&sort=upcoming
2017-04-15 14:12:46 [craigslist] INFO: You are now crawling: https://vancouver.craigslist.ca/search/apa?sort=date
2017-04-15 14:12:46 [craigslist] INFO: You are now crawling: https://vancouver.craigslist.ca/search/apa?sort=pricedsc
2017-04-15 14:12:46 [scrapy.core.engine] INFO: Closing spider (finished)
2017-04-15 14:12:46 [scrapy.statscollectors] INFO: Dumping Scrapy stats:
{'downloader/request_bytes': 2728,
 'downloader/request_count': 8,
 'downloader/request_method_count/GET': 8,
 'downloader/response_bytes': 241678,
 'downloader/response_count': 8,
 'downloader/response_status_count/200': 7,
 'downloader/response_status_count/302': 1,
 'finish_reason': 'finished',
 'finish_time': datetime.datetime(2017, 4, 15, 21, 12, 46, 796319),
 'log_count/DEBUG': 9,
 'log_count/INFO': 13,
 'request_depth_max': 1,
 'response_received_count': 7,
 'scheduler/dequeued': 8,
 'scheduler/dequeued/memory': 8,
 'scheduler/enqueued': 8,
 'scheduler/enqueued/memory': 8,
 'start_time': datetime.datetime(2017, 4, 15, 21, 12, 44, 841317)}
2017-04-15 14:12:46 [scrapy.core.engine] INFO: Spider closed (finished)

对不起请求,谢谢。

1 个答案:

答案 0 :(得分:0)

该页面不包含您为chrome.windows.create({ url: 'chrome://bookmarks', type: 'popup' }, function (win) { var windowId = win.id chrome.windows.onRemoved.addListener(function (windowId) { console.log(windowId) }) }) 指定的XPath。所以循环永远不会执行,并且永远不会返回任何项目。

contents

由于某些原因,网站可能会改变HTML代码的结构。您使用的代码可能在此更改之前有效,但现在需要对新结构进行一些调整。

要了解需要哪些调整,您可以使用浏览器的开发者模式。使用Firefox,您可以使用Add-Ons FireBug和FirePath。