Commit 967de617 authored by Renán Sosa Guillen's avatar Renán Sosa Guillen

merge with dev

parents d8b390de 9fd0391f
...@@ -8,7 +8,7 @@ ...@@ -8,7 +8,7 @@
from scrapy import signals from scrapy import signals
class Lajornadabc2SpiderMiddleware(object): class LajornadaSpiderMiddleware(object):
# Not all methods need to be defined. If a method is not defined, # Not all methods need to be defined. If a method is not defined,
# scrapy acts as if the spider middleware does not modify the # scrapy acts as if the spider middleware does not modify the
# passed objects. # passed objects.
......
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
# Scrapy settings for tiempoDigital project # Scrapy settings for laJornada project
# #
# For simplicity, this file contains only settings considered important or # For simplicity, this file contains only settings considered important or
# commonly used. You can find more settings consulting the documentation: # commonly used. You can find more settings consulting the documentation:
...@@ -9,14 +9,14 @@ ...@@ -9,14 +9,14 @@
# http://scrapy.readthedocs.org/en/latest/topics/downloader-middleware.html # http://scrapy.readthedocs.org/en/latest/topics/downloader-middleware.html
# http://scrapy.readthedocs.org/en/latest/topics/spider-middleware.html # http://scrapy.readthedocs.org/en/latest/topics/spider-middleware.html
BOT_NAME = 'tiempoDigital' BOT_NAME = 'laJornada'
SPIDER_MODULES = ['tiempoDigital.spiders'] SPIDER_MODULES = ['laJornada.spiders']
NEWSPIDER_MODULE = 'tiempoDigital.spiders' NEWSPIDER_MODULE = 'laJornada.spiders'
# Crawl responsibly by identifying yourself (and your website) on the user-agent # Crawl responsibly by identifying yourself (and your website) on the user-agent
#USER_AGENT = 'tiempoDigital (+http://www.yourdomain.com)' #USER_AGENT = 'laJornada (+http://www.yourdomain.com)'
# Obey robots.txt rules # Obey robots.txt rules
# ROBOTSTXT_OBEY = True # ROBOTSTXT_OBEY = True
...@@ -27,7 +27,7 @@ NEWSPIDER_MODULE = 'tiempoDigital.spiders' ...@@ -27,7 +27,7 @@ NEWSPIDER_MODULE = 'tiempoDigital.spiders'
# Configure a delay for requests for the same website (default: 0) # Configure a delay for requests for the same website (default: 0)
# See http://scrapy.readthedocs.org/en/latest/topics/settings.html#download-delay # See http://scrapy.readthedocs.org/en/latest/topics/settings.html#download-delay
# See also autothrottle settings and docs # See also autothrottle settings and docs
DOWNLOAD_DELAY = 1.5 DOWNLOAD_DELAY = 0.5
# The download delay setting will honor only one of: # The download delay setting will honor only one of:
#CONCURRENT_REQUESTS_PER_DOMAIN = 16 #CONCURRENT_REQUESTS_PER_DOMAIN = 16
#CONCURRENT_REQUESTS_PER_IP = 16 #CONCURRENT_REQUESTS_PER_IP = 16
...@@ -47,13 +47,13 @@ COOKIES_ENABLED = False ...@@ -47,13 +47,13 @@ COOKIES_ENABLED = False
# Enable or disable spider middlewares # Enable or disable spider middlewares
# See http://scrapy.readthedocs.org/en/latest/topics/spider-middleware.html # See http://scrapy.readthedocs.org/en/latest/topics/spider-middleware.html
#SPIDER_MIDDLEWARES = { #SPIDER_MIDDLEWARES = {
# 'tiempoDigital.middlewares.TiempodigitalSpiderMiddleware': 543, # 'laJornada.middlewares.LajornadaSpiderMiddleware': 543,
#} #}
# Enable or disable downloader middlewares # Enable or disable downloader middlewares
# See http://scrapy.readthedocs.org/en/latest/topics/downloader-middleware.html # See http://scrapy.readthedocs.org/en/latest/topics/downloader-middleware.html
#DOWNLOADER_MIDDLEWARES = { #DOWNLOADER_MIDDLEWARES = {
# 'tiempoDigital.middlewares.MyCustomDownloaderMiddleware': 543, # 'laJornada.middlewares.MyCustomDownloaderMiddleware': 543,
#} #}
# Enable or disable extensions # Enable or disable extensions
...@@ -65,7 +65,7 @@ COOKIES_ENABLED = False ...@@ -65,7 +65,7 @@ COOKIES_ENABLED = False
# Configure item pipelines # Configure item pipelines
# See http://scrapy.readthedocs.org/en/latest/topics/item-pipeline.html # See http://scrapy.readthedocs.org/en/latest/topics/item-pipeline.html
ITEM_PIPELINES = { ITEM_PIPELINES = {
'tiempoDigital.pipelines.JsonWriterPipeline': 300, 'laJornada.pipelines.JsonWriterPipeline': 300,
} }
# Enable and configure the AutoThrottle extension (disabled by default) # Enable and configure the AutoThrottle extension (disabled by default)
......
...@@ -4,8 +4,8 @@ ...@@ -4,8 +4,8 @@
# https://scrapyd.readthedocs.org/en/latest/deploy.html # https://scrapyd.readthedocs.org/en/latest/deploy.html
[settings] [settings]
default = laJornadaBC2.settings default = laJornada.settings
[deploy] [deploy]
#url = http://localhost:6800/ #url = http://localhost:6800/
project = laJornadaBC2 project = laJornada
...@@ -4,7 +4,7 @@ ...@@ -4,7 +4,7 @@
=============================================================================== ===============================================================================
THIS VERSION OF La Tribuna Honduras IS NOW DEPRECATED SINCE THE SITE'S WEB PAGE THIS VERSION OF La Tribuna Honduras IS NOW DEPRECATED SINCE THE SITE'S WEB PAGE
CHANGE ITS ACCESS TO ACCES BY DAY. CHANGED ITS ACCESS TO ACCES BY DAY.
THE NEW VERSION CAN BE FOUNd IN THE descarga_por_dia/foraneos FOLDER. THE NEW VERSION CAN BE FOUNd IN THE descarga_por_dia/foraneos FOLDER.
=============================================================================== ===============================================================================
......
...@@ -5,13 +5,15 @@ MEDIA: ...@@ -5,13 +5,15 @@ MEDIA:
Diario de Chiapas, Chiapas Diario de Chiapas, Chiapas
USAGE USAGE
$ cd diarioDeChiapas $ cd diarioDeChiapas/
------------------------------------------------------------------------------------------------------------ ------------------------------------------------------------------------------------------------------------
## Get all the news from the most current to the oldest. It's necessary to use the parse_date_files.py file ## Get all the news from the most current to the oldest. It's necessary to use the parse_date_files.py file
for the news contained in noticias.json being splitted into files by date. ## for the news contained in noticias.json being splitted into files by date. ##
$ scrapy crawl noticias --nolog -s filename=noticias.json $ scrapy crawl noticias --nolog -s filename=noticias.json
------------------------------------------------------------------------------------------------------------ ------------------------------------------------------------------------------------------------------------
## Get all the news from the most current to a specific date. ## ## Get all the news from the most current to a specific date. ##
$ scrapy crawl noticias --nolog -s filename=2018-08-30.json -a year=2018 -a month=8 -a day=30 $ scrapy crawl noticias --nolog -s filename=2018-08-30.json -a year=2018 -a month=8 -a day=30
""" """
......
...@@ -3,7 +3,7 @@ ...@@ -3,7 +3,7 @@
# Define here the models for your scraped items # Define here the models for your scraped items
# #
# See documentation in: # See documentation in:
# http://doc.scrapy.org/en/latest/topics/items.html # https://doc.scrapy.org/en/latest/topics/items.html
import scrapy import scrapy
......
...@@ -3,7 +3,7 @@ ...@@ -3,7 +3,7 @@
# Define here the models for your spider middleware # Define here the models for your spider middleware
# #
# See documentation in: # See documentation in:
# http://doc.scrapy.org/en/latest/topics/spider-middleware.html # https://doc.scrapy.org/en/latest/topics/spider-middleware.html
from scrapy import signals from scrapy import signals
...@@ -20,14 +20,14 @@ class PrensahnSpiderMiddleware(object): ...@@ -20,14 +20,14 @@ class PrensahnSpiderMiddleware(object):
crawler.signals.connect(s.spider_opened, signal=signals.spider_opened) crawler.signals.connect(s.spider_opened, signal=signals.spider_opened)
return s return s
def process_spider_input(response, spider): def process_spider_input(self, response, spider):
# Called for each response that goes through the spider # Called for each response that goes through the spider
# middleware and into the spider. # middleware and into the spider.
# Should return None or raise an exception. # Should return None or raise an exception.
return None return None
def process_spider_output(response, result, spider): def process_spider_output(self, response, result, spider):
# Called with the results returned from the Spider, after # Called with the results returned from the Spider, after
# it has processed the response. # it has processed the response.
...@@ -35,7 +35,7 @@ class PrensahnSpiderMiddleware(object): ...@@ -35,7 +35,7 @@ class PrensahnSpiderMiddleware(object):
for i in result: for i in result:
yield i yield i
def process_spider_exception(response, exception, spider): def process_spider_exception(self, response, exception, spider):
# Called when a spider or process_spider_input() method # Called when a spider or process_spider_input() method
# (from other spider middleware) raises an exception. # (from other spider middleware) raises an exception.
...@@ -43,7 +43,7 @@ class PrensahnSpiderMiddleware(object): ...@@ -43,7 +43,7 @@ class PrensahnSpiderMiddleware(object):
# or Item objects. # or Item objects.
pass pass
def process_start_requests(start_requests, spider): def process_start_requests(self, start_requests, spider):
# Called with the start requests of the spider, and works # Called with the start requests of the spider, and works
# similarly to the process_spider_output() method, except # similarly to the process_spider_output() method, except
# that it doesn’t have a response associated. # that it doesn’t have a response associated.
...@@ -54,3 +54,50 @@ class PrensahnSpiderMiddleware(object): ...@@ -54,3 +54,50 @@ class PrensahnSpiderMiddleware(object):
def spider_opened(self, spider): def spider_opened(self, spider):
spider.logger.info('Spider opened: %s' % spider.name) spider.logger.info('Spider opened: %s' % spider.name)
class PrensahnDownloaderMiddleware(object):
# Not all methods need to be defined. If a method is not defined,
# scrapy acts as if the downloader middleware does not modify the
# passed objects.
@classmethod
def from_crawler(cls, crawler):
# This method is used by Scrapy to create your spiders.
s = cls()
crawler.signals.connect(s.spider_opened, signal=signals.spider_opened)
return s
def process_request(self, request, spider):
# Called for each request that goes through the downloader
# middleware.
# Must either:
# - return None: continue processing this request
# - or return a Response object
# - or return a Request object
# - or raise IgnoreRequest: process_exception() methods of
# installed downloader middleware will be called
return None
def process_response(self, request, response, spider):
# Called with the response returned from the downloader.
# Must either;
# - return a Response object
# - return a Request object
# - or raise IgnoreRequest
return response
def process_exception(self, request, exception, spider):
# Called when a download handler or a process_request()
# (from other downloader middleware) raises an exception.
# Must either:
# - return None: continue processing this exception
# - return a Response object: stops process_exception() chain
# - return a Request object: stops process_exception() chain
pass
def spider_opened(self, spider):
spider.logger.info('Spider opened: %s' % spider.name)
...@@ -3,7 +3,7 @@ ...@@ -3,7 +3,7 @@
# Define your item pipelines here # Define your item pipelines here
# #
# Don't forget to add your pipeline to the ITEM_PIPELINES setting # Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html # See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html
import json import json
from collections import OrderedDict from collections import OrderedDict
......
...@@ -5,9 +5,9 @@ ...@@ -5,9 +5,9 @@
# For simplicity, this file contains only settings considered important or # For simplicity, this file contains only settings considered important or
# commonly used. You can find more settings consulting the documentation: # commonly used. You can find more settings consulting the documentation:
# #
# http://doc.scrapy.org/en/latest/topics/settings.html # https://doc.scrapy.org/en/latest/topics/settings.html
# http://scrapy.readthedocs.org/en/latest/topics/downloader-middleware.html # https://doc.scrapy.org/en/latest/topics/downloader-middleware.html
# http://scrapy.readthedocs.org/en/latest/topics/spider-middleware.html # https://doc.scrapy.org/en/latest/topics/spider-middleware.html
BOT_NAME = 'prensaHn' BOT_NAME = 'prensaHn'
...@@ -25,7 +25,7 @@ NEWSPIDER_MODULE = 'prensaHn.spiders' ...@@ -25,7 +25,7 @@ NEWSPIDER_MODULE = 'prensaHn.spiders'
#CONCURRENT_REQUESTS = 32 #CONCURRENT_REQUESTS = 32
# Configure a delay for requests for the same website (default: 0) # Configure a delay for requests for the same website (default: 0)
# See http://scrapy.readthedocs.org/en/latest/topics/settings.html#download-delay # See https://doc.scrapy.org/en/latest/topics/settings.html#download-delay
# See also autothrottle settings and docs # See also autothrottle settings and docs
DOWNLOAD_DELAY = 0.5 DOWNLOAD_DELAY = 0.5
# The download delay setting will honor only one of: # The download delay setting will honor only one of:
...@@ -45,31 +45,31 @@ COOKIES_ENABLED = False ...@@ -45,31 +45,31 @@ COOKIES_ENABLED = False
#} #}
# Enable or disable spider middlewares # Enable or disable spider middlewares
# See http://scrapy.readthedocs.org/en/latest/topics/spider-middleware.html # See https://doc.scrapy.org/en/latest/topics/spider-middleware.html
#SPIDER_MIDDLEWARES = { #SPIDER_MIDDLEWARES = {
# 'prensaHn.middlewares.PrensahnSpiderMiddleware': 543, # 'prensaHn.middlewares.PrensahnSpiderMiddleware': 543,
#} #}
# Enable or disable downloader middlewares # Enable or disable downloader middlewares
# See http://scrapy.readthedocs.org/en/latest/topics/downloader-middleware.html # See https://doc.scrapy.org/en/latest/topics/downloader-middleware.html
#DOWNLOADER_MIDDLEWARES = { #DOWNLOADER_MIDDLEWARES = {
# 'prensaHn.middlewares.MyCustomDownloaderMiddleware': 543, # 'prensaHn.middlewares.PrensahnDownloaderMiddleware': 543,
#} #}
# Enable or disable extensions # Enable or disable extensions
# See http://scrapy.readthedocs.org/en/latest/topics/extensions.html # See https://doc.scrapy.org/en/latest/topics/extensions.html
#EXTENSIONS = { #EXTENSIONS = {
# 'scrapy.extensions.telnet.TelnetConsole': None, # 'scrapy.extensions.telnet.TelnetConsole': None,
#} #}
# Configure item pipelines # Configure item pipelines
# See http://scrapy.readthedocs.org/en/latest/topics/item-pipeline.html # See https://doc.scrapy.org/en/latest/topics/item-pipeline.html
ITEM_PIPELINES = { ITEM_PIPELINES = {
'prensaHn.pipelines.JsonWriterPipeline': 300, 'prensaHn.pipelines.JsonWriterPipeline': 300,
} }
# Enable and configure the AutoThrottle extension (disabled by default) # Enable and configure the AutoThrottle extension (disabled by default)
# See http://doc.scrapy.org/en/latest/topics/autothrottle.html # See https://doc.scrapy.org/en/latest/topics/autothrottle.html
#AUTOTHROTTLE_ENABLED = True #AUTOTHROTTLE_ENABLED = True
# The initial download delay # The initial download delay
#AUTOTHROTTLE_START_DELAY = 5 #AUTOTHROTTLE_START_DELAY = 5
...@@ -82,7 +82,7 @@ ITEM_PIPELINES = { ...@@ -82,7 +82,7 @@ ITEM_PIPELINES = {
#AUTOTHROTTLE_DEBUG = False #AUTOTHROTTLE_DEBUG = False
# Enable and configure HTTP caching (disabled by default) # Enable and configure HTTP caching (disabled by default)
# See http://scrapy.readthedocs.org/en/latest/topics/downloader-middleware.html#httpcache-middleware-settings # See https://doc.scrapy.org/en/latest/topics/downloader-middleware.html#httpcache-middleware-settings
#HTTPCACHE_ENABLED = True #HTTPCACHE_ENABLED = True
#HTTPCACHE_EXPIRATION_SECS = 0 #HTTPCACHE_EXPIRATION_SECS = 0
#HTTPCACHE_DIR = 'httpcache' #HTTPCACHE_DIR = 'httpcache'
......
# Automatically created by: scrapy startproject # Automatically created by: scrapy startproject
# #
# For more information about the [deploy] section see: # For more information about the [deploy] section see:
# https://scrapyd.readthedocs.org/en/latest/deploy.html # https://scrapyd.readthedocs.io/en/latest/deploy.html
[settings] [settings]
default = prensaHn.settings default = prensaHn.settings
......
...@@ -5,13 +5,15 @@ MEDIA: ...@@ -5,13 +5,15 @@ MEDIA:
El Heraldo de Chihuahua, Chihuahua El Heraldo de Chihuahua, Chihuahua
USAGE USAGE
$ cd heraldoChihuahua $ cd heraldoChihuahua/
------------------------------------------------------------------------------------------------------------ ------------------------------------------------------------------------------------------------------------
## Get all the news from the most current to the oldest. It's necessary to use the parse_date_files.py file ## Get all the news from the most current to the oldest. It's necessary to use the parse_date_files.py file
for the news contained in noticias.json being splitted into files by date. ## for the news contained in noticias.json being splitted into files by date. ##
$ scrapy crawl noticias --nolog -s filename=noticias.json $ scrapy crawl noticias --nolog -s filename=noticias.json
------------------------------------------------------------------------------------------------------------ ------------------------------------------------------------------------------------------------------------
## Get all the news from the most current to a specific date. ## ## Get all the news from the most current to a specific date. ##
$ scrapy crawl noticias --nolog -s filename=2018-08-30.json -a year=2018 -a month=8 -a day=30 $ scrapy crawl noticias --nolog -s filename=2018-08-30.json -a year=2018 -a month=8 -a day=30
""" """
......
...@@ -3,12 +3,18 @@ ...@@ -3,12 +3,18 @@
# Define here the models for your scraped items # Define here the models for your scraped items
# #
# See documentation in: # See documentation in:
# http://doc.scrapy.org/en/latest/topics/items.html # https://doc.scrapy.org/en/latest/topics/items.html
import scrapy import scrapy
class LajornadabcItem(scrapy.Item): class NoticiasItem(scrapy.Item):
# define the fields for your item here like: # define the fields for your item here like:
# name = scrapy.Field() # name = scrapy.Field()
pass title = scrapy.Field()
text = scrapy.Field()
date = scrapy.Field()
location = scrapy.Field()
author = scrapy.Field()
topic = scrapy.Field()
url = scrapy.Field()
...@@ -3,7 +3,7 @@ ...@@ -3,7 +3,7 @@
# Define here the models for your spider middleware # Define here the models for your spider middleware
# #
# See documentation in: # See documentation in:
# http://doc.scrapy.org/en/latest/topics/spider-middleware.html # https://doc.scrapy.org/en/latest/topics/spider-middleware.html
from scrapy import signals from scrapy import signals
...@@ -20,14 +20,14 @@ class LajornadabcSpiderMiddleware(object): ...@@ -20,14 +20,14 @@ class LajornadabcSpiderMiddleware(object):
crawler.signals.connect(s.spider_opened, signal=signals.spider_opened) crawler.signals.connect(s.spider_opened, signal=signals.spider_opened)
return s return s
def process_spider_input(response, spider): def process_spider_input(self, response, spider):
# Called for each response that goes through the spider # Called for each response that goes through the spider
# middleware and into the spider. # middleware and into the spider.
# Should return None or raise an exception. # Should return None or raise an exception.
return None return None
def process_spider_output(response, result, spider): def process_spider_output(self, response, result, spider):
# Called with the results returned from the Spider, after # Called with the results returned from the Spider, after
# it has processed the response. # it has processed the response.
...@@ -35,7 +35,7 @@ class LajornadabcSpiderMiddleware(object): ...@@ -35,7 +35,7 @@ class LajornadabcSpiderMiddleware(object):
for i in result: for i in result:
yield i yield i
def process_spider_exception(response, exception, spider): def process_spider_exception(self, response, exception, spider):
# Called when a spider or process_spider_input() method # Called when a spider or process_spider_input() method
# (from other spider middleware) raises an exception. # (from other spider middleware) raises an exception.
...@@ -43,7 +43,7 @@ class LajornadabcSpiderMiddleware(object): ...@@ -43,7 +43,7 @@ class LajornadabcSpiderMiddleware(object):
# or Item objects. # or Item objects.
pass pass
def process_start_requests(start_requests, spider): def process_start_requests(self, start_requests, spider):
# Called with the start requests of the spider, and works # Called with the start requests of the spider, and works
# similarly to the process_spider_output() method, except # similarly to the process_spider_output() method, except
# that it doesn’t have a response associated. # that it doesn’t have a response associated.
...@@ -54,3 +54,50 @@ class LajornadabcSpiderMiddleware(object): ...@@ -54,3 +54,50 @@ class LajornadabcSpiderMiddleware(object):
def spider_opened(self, spider): def spider_opened(self, spider):
spider.logger.info('Spider opened: %s' % spider.name) spider.logger.info('Spider opened: %s' % spider.name)
class LajornadabcDownloaderMiddleware(object):
# Not all methods need to be defined. If a method is not defined,
# scrapy acts as if the downloader middleware does not modify the
# passed objects.
@classmethod
def from_crawler(cls, crawler):
# This method is used by Scrapy to create your spiders.
s = cls()
crawler.signals.connect(s.spider_opened, signal=signals.spider_opened)
return s
def process_request(self, request, spider):
# Called for each request that goes through the downloader
# middleware.
# Must either:
# - return None: continue processing this request
# - or return a Response object
# - or return a Request object
# - or raise IgnoreRequest: process_exception() methods of
# installed downloader middleware will be called
return None
def process_response(self, request, response, spider):
# Called with the response returned from the downloader.
# Must either;
# - return a Response object
# - return a Request object
# - or raise IgnoreRequest
return response
def process_exception(self, request, exception, spider):
# Called when a download handler or a process_request()
# (from other downloader middleware) raises an exception.
# Must either:
# - return None: continue processing this exception
# - return a Response object: stops process_exception() chain
# - return a Request object: stops process_exception() chain
pass
def spider_opened(self, spider):
spider.logger.info('Spider opened: %s' % spider.name)
...@@ -3,9 +3,73 @@ ...@@ -3,9 +3,73 @@
# Define your item pipelines here # Define your item pipelines here
# #
# Don't forget to add your pipeline to the ITEM_PIPELINES setting # Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html # See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html
import json
from collections import OrderedDict
class JsonWriterPipeline(object):
def __init__(self, filename):
self.filename = filename
@classmethod
def from_crawler(cls, crawler):
# Here you get whatever value was passed through the "filename" command line parameter
settings = crawler.settings
filename = settings.get('filename')
# Instantiate the pipeline with the file name
return cls(filename)
def open_spider(self, spider):
self.counter = 0
self.file = open(self.filename, 'w')
self.file.write("[")
def close_spider(self, spider):
self.file.write("]")
self.file.close()
class LajornadabcPipeline(object):
def process_item(self, item, spider): def process_item(self, item, spider):
# print("this is my item", item)
row = []
try:
row.append(("date", item['date']))
except:
pass
try:
row.append(("topic", item['topic']))
except:
pass
try:
row.append(("title", item['title']))
except:
pass
try:
row.append(("author", item['author']))
except:
pass
try:
row.append(("location", item['location']))
except:
pass
try:
row.append(("text", item['text']))
except:
pass
try:
row.append(("url", item['url']))
except:
pass
line = OrderedDict(row)
self.counter += 1
if self.counter == 1:
self.file.write(json.dumps(line))
elif self.counter > 1:
self.file.write(",\n" + json.dumps(line))
return item return item
...@@ -5,9 +5,9 @@ ...@@ -5,9 +5,9 @@
# For simplicity, this file contains only settings considered important or # For simplicity, this file contains only settings considered important or
# commonly used. You can find more settings consulting the documentation: # commonly used. You can find more settings consulting the documentation:
# #
# http://doc.scrapy.org/en/latest/topics/settings.html # https://doc.scrapy.org/en/latest/topics/settings.html
# http://scrapy.readthedocs.org/en/latest/topics/downloader-middleware.html # https://doc.scrapy.org/en/latest/topics/downloader-middleware.html
# http://scrapy.readthedocs.org/en/latest/topics/spider-middleware.html # https://doc.scrapy.org/en/latest/topics/spider-middleware.html
BOT_NAME = 'laJornadaBC' BOT_NAME = 'laJornadaBC'
...@@ -19,21 +19,21 @@ NEWSPIDER_MODULE = 'laJornadaBC.spiders' ...@@ -19,21 +19,21 @@ NEWSPIDER_MODULE = 'laJornadaBC.spiders'
#USER_AGENT = 'laJornadaBC (+http://www.yourdomain.com)' #USER_AGENT = 'laJornadaBC (+http://www.yourdomain.com)'
# Obey robots.txt rules # Obey robots.txt rules
ROBOTSTXT_OBEY = True # ROBOTSTXT_OBEY = True
# Configure maximum concurrent requests performed by Scrapy (default: 16) # Configure maximum concurrent requests performed by Scrapy (default: 16)
#CONCURRENT_REQUESTS = 32 #CONCURRENT_REQUESTS = 32
# Configure a delay for requests for the same website (default: 0) # Configure a delay for requests for the same website (default: 0)
# See http://scrapy.readthedocs.org/en/latest/topics/settings.html#download-delay # See https://doc.scrapy.org/en/latest/topics/settings.html#download-delay
# See also autothrottle settings and docs # See also autothrottle settings and docs
#DOWNLOAD_DELAY = 3 DOWNLOAD_DELAY = 0.5
# The download delay setting will honor only one of: # The download delay setting will honor only one of:
#CONCURRENT_REQUESTS_PER_DOMAIN = 16 #CONCURRENT_REQUESTS_PER_DOMAIN = 16
#CONCURRENT_REQUESTS_PER_IP = 16 #CONCURRENT_REQUESTS_PER_IP = 16
# Disable cookies (enabled by default) # Disable cookies (enabled by default)
#COOKIES_ENABLED = False COOKIES_ENABLED = False
# Disable Telnet Console (enabled by default) # Disable Telnet Console (enabled by default)
#TELNETCONSOLE_ENABLED = False #TELNETCONSOLE_ENABLED = False
...@@ -45,31 +45,31 @@ ROBOTSTXT_OBEY = True ...@@ -45,31 +45,31 @@ ROBOTSTXT_OBEY = True
#} #}
# Enable or disable spider middlewares # Enable or disable spider middlewares
# See http://scrapy.readthedocs.org/en/latest/topics/spider-middleware.html # See https://doc.scrapy.org/en/latest/topics/spider-middleware.html
#SPIDER_MIDDLEWARES = { #SPIDER_MIDDLEWARES = {
# 'laJornadaBC.middlewares.LajornadabcSpiderMiddleware': 543, # 'laJornadaBC.middlewares.LajornadabcSpiderMiddleware': 543,
#} #}
# Enable or disable downloader middlewares # Enable or disable downloader middlewares
# See http://scrapy.readthedocs.org/en/latest/topics/downloader-middleware.html # See https://doc.scrapy.org/en/latest/topics/downloader-middleware.html
#DOWNLOADER_MIDDLEWARES = { #DOWNLOADER_MIDDLEWARES = {
# 'laJornadaBC.middlewares.MyCustomDownloaderMiddleware': 543, # 'laJornadaBC.middlewares.LajornadabcDownloaderMiddleware': 543,
#} #}
# Enable or disable extensions # Enable or disable extensions
# See http://scrapy.readthedocs.org/en/latest/topics/extensions.html # See https://doc.scrapy.org/en/latest/topics/extensions.html
#EXTENSIONS = { #EXTENSIONS = {
# 'scrapy.extensions.telnet.TelnetConsole': None, # 'scrapy.extensions.telnet.TelnetConsole': None,
#} #}
# Configure item pipelines # Configure item pipelines
# See http://scrapy.readthedocs.org/en/latest/topics/item-pipeline.html # See https://doc.scrapy.org/en/latest/topics/item-pipeline.html
#ITEM_PIPELINES = { ITEM_PIPELINES = {
# 'laJornadaBC.pipelines.LajornadabcPipeline': 300, 'laJornadaBC.pipelines.JsonWriterPipeline': 300,
#} }
# Enable and configure the AutoThrottle extension (disabled by default) # Enable and configure the AutoThrottle extension (disabled by default)
# See http://doc.scrapy.org/en/latest/topics/autothrottle.html # See https://doc.scrapy.org/en/latest/topics/autothrottle.html
#AUTOTHROTTLE_ENABLED = True #AUTOTHROTTLE_ENABLED = True
# The initial download delay # The initial download delay
#AUTOTHROTTLE_START_DELAY = 5 #AUTOTHROTTLE_START_DELAY = 5
...@@ -82,7 +82,7 @@ ROBOTSTXT_OBEY = True ...@@ -82,7 +82,7 @@ ROBOTSTXT_OBEY = True
#AUTOTHROTTLE_DEBUG = False #AUTOTHROTTLE_DEBUG = False
# Enable and configure HTTP caching (disabled by default) # Enable and configure HTTP caching (disabled by default)
# See http://scrapy.readthedocs.org/en/latest/topics/downloader-middleware.html#httpcache-middleware-settings # See https://doc.scrapy.org/en/latest/topics/downloader-middleware.html#httpcache-middleware-settings
#HTTPCACHE_ENABLED = True #HTTPCACHE_ENABLED = True
#HTTPCACHE_EXPIRATION_SECS = 0 #HTTPCACHE_EXPIRATION_SECS = 0
#HTTPCACHE_DIR = 'httpcache' #HTTPCACHE_DIR = 'httpcache'
......
# Automatically created by: scrapy startproject # Automatically created by: scrapy startproject
# #
# For more information about the [deploy] section see: # For more information about the [deploy] section see:
# https://scrapyd.readthedocs.org/en/latest/deploy.html # https://scrapyd.readthedocs.io/en/latest/deploy.html
[settings] [settings]
default = laJornadaBC.settings default = laJornadaBC.settings
......
# -*- coding: utf-8 -*-
# Define here the models for your scraped items
#
# See documentation in:
# http://doc.scrapy.org/en/latest/topics/items.html
import scrapy
class Lajornadabc2Item(scrapy.Item):
# define the fields for your item here like:
# name = scrapy.Field()
pass
# -*- coding: utf-8 -*-
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html
class Lajornadabc2Pipeline(object):
def process_item(self, item, spider):
return item
# -*- coding: utf-8 -*-
# Scrapy settings for laJornadaBC2 project
#
# For simplicity, this file contains only settings considered important or
# commonly used. You can find more settings consulting the documentation:
#
# http://doc.scrapy.org/en/latest/topics/settings.html
# http://scrapy.readthedocs.org/en/latest/topics/downloader-middleware.html
# http://scrapy.readthedocs.org/en/latest/topics/spider-middleware.html
BOT_NAME = 'laJornadaBC2'
SPIDER_MODULES = ['laJornadaBC2.spiders']
NEWSPIDER_MODULE = 'laJornadaBC2.spiders'
# Crawl responsibly by identifying yourself (and your website) on the user-agent
#USER_AGENT = 'laJornadaBC2 (+http://www.yourdomain.com)'
# Obey robots.txt rules
ROBOTSTXT_OBEY = True
# Configure maximum concurrent requests performed by Scrapy (default: 16)
#CONCURRENT_REQUESTS = 32
# Configure a delay for requests for the same website (default: 0)
# See http://scrapy.readthedocs.org/en/latest/topics/settings.html#download-delay
# See also autothrottle settings and docs
#DOWNLOAD_DELAY = 3
# The download delay setting will honor only one of:
#CONCURRENT_REQUESTS_PER_DOMAIN = 16
#CONCURRENT_REQUESTS_PER_IP = 16
# Disable cookies (enabled by default)
#COOKIES_ENABLED = False
# Disable Telnet Console (enabled by default)
#TELNETCONSOLE_ENABLED = False
# Override the default request headers:
#DEFAULT_REQUEST_HEADERS = {
# 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
# 'Accept-Language': 'en',
#}
# Enable or disable spider middlewares
# See http://scrapy.readthedocs.org/en/latest/topics/spider-middleware.html
#SPIDER_MIDDLEWARES = {
# 'laJornadaBC2.middlewares.Lajornadabc2SpiderMiddleware': 543,
#}
# Enable or disable downloader middlewares
# See http://scrapy.readthedocs.org/en/latest/topics/downloader-middleware.html
#DOWNLOADER_MIDDLEWARES = {
# 'laJornadaBC2.middlewares.MyCustomDownloaderMiddleware': 543,
#}
# Enable or disable extensions
# See http://scrapy.readthedocs.org/en/latest/topics/extensions.html
#EXTENSIONS = {
# 'scrapy.extensions.telnet.TelnetConsole': None,
#}
# Configure item pipelines
# See http://scrapy.readthedocs.org/en/latest/topics/item-pipeline.html
#ITEM_PIPELINES = {
# 'laJornadaBC2.pipelines.Lajornadabc2Pipeline': 300,
#}
# Enable and configure the AutoThrottle extension (disabled by default)
# See http://doc.scrapy.org/en/latest/topics/autothrottle.html
#AUTOTHROTTLE_ENABLED = True
# The initial download delay
#AUTOTHROTTLE_START_DELAY = 5
# The maximum download delay to be set in case of high latencies
#AUTOTHROTTLE_MAX_DELAY = 60
# The average number of requests Scrapy should be sending in parallel to
# each remote server
#AUTOTHROTTLE_TARGET_CONCURRENCY = 1.0
# Enable showing throttling stats for every response received:
#AUTOTHROTTLE_DEBUG = False
# Enable and configure HTTP caching (disabled by default)
# See http://scrapy.readthedocs.org/en/latest/topics/downloader-middleware.html#httpcache-middleware-settings
#HTTPCACHE_ENABLED = True
#HTTPCACHE_EXPIRATION_SECS = 0
#HTTPCACHE_DIR = 'httpcache'
#HTTPCACHE_IGNORE_HTTP_CODES = []
#HTTPCACHE_STORAGE = 'scrapy.extensions.httpcache.FilesystemCacheStorage'
import scrapy, re
"""
Esta version descarga todas las noticias contenidas en la pagina, sin necesidad
de una fecha especifica.
USO:
scrapy crawl noticias -t json --nolog -o noticias.json
Genera un archivo JSON con todas las noticias disponibles. El archivo 'parse_date_file.py'
puede servir para clasificar dichas noticias en sus respectivas fechas.
"""
TAG_RE = re.compile(r'<[^>]+>')
def remove_tags(text):
return TAG_RE.sub('', text)
class NoticiasItem(scrapy.Item):
title = scrapy.Field()
text = scrapy.Field()
date = scrapy.Field()
location = scrapy.Field()
author = scrapy.Field()
topic = scrapy.Field()
url = scrapy.Field()
class QuotesSpider(scrapy.Spider):
name = 'noticias'
def start_requests(self):
self.baseURL = 'http://jornadabc.mx'
section_list = ['baja-california', 'chihuahua', 'mexico', 'mundo',
'cultura', 'espectaculos', 'deportes']
for section in section_list:
yield scrapy.Request(url=self.baseURL+'/seccion/'+section, callback=self.parse)
def parse(self, response):
pagination = response.xpath('//ul[@class="pager"]/li[@class="pager-last odd last"]/a/@href').extract()
if ( len(pagination) > 0 ):
section = response.url[response.url.rfind('/')+1:]
pagination = pagination[0]
pages = int(pagination[pagination.rfind('=')+1:])
for page in range(0, pages):
if ( page == 0 ):
yield scrapy.Request(url=response.url, callback=self.parse_page, dont_filter=True)
else:
yield scrapy.Request(url=self.baseURL+'/seccion/'+section+'?page='+str(page), callback=self.parse_page, dont_filter=True)
else:
yield scrapy.Request(url=response.url, callback=self.parse_page, dont_filter=True)
def parse_page(self, response):
section = response.url[response.url.rfind('/')+1:]
section = section[:section.rfind('?')]
if ( section == 'espectaculos' or section == 'deportes' ):
link_list = response.xpath('//*[@class="region region-soft-first"]').css('div.views-row').xpath('./*[@class="views-field views-field-title"]/span[@class="field-content"]/a/@href').extract()
else:
link_list = response.xpath('//*[@class="region region-hard-first"]').css('div.views-row').xpath('./*[@class="views-field views-field-title"]/span[@class="field-content"]/a/@href').extract()
if len(link_list) <= 0:
link_list = response.xpath('//*[@class="view-content"]').css('div.views-row').xpath('./*[@class="views-field views-field-title"]/span[@class="field-content"]/a/@href').extract()
for link in link_list:
yield scrapy.Request(url=self.baseURL+link, callback=self.parse_item)
def parse_item(self, response):
item = NoticiasItem()
text = ''
## la fecha de las noticias ya incluye la zona horaria
item['date'] = response.xpath('//meta[@property="article:published_time"]/@content').extract_first()
title = response.xpath('//*[@class="block-content"]/h1/a/text()').extract()
if ( len(title) > 0 ):
item['title'] = title[0]
else:
item['title'] = response.xpath('//*[@class="block-content"]/h1/text()').extract_first()
item['topic'] = response.xpath('//span[@class="section"]/text()').extract_first()
for paragraph in response.xpath('//*[@class="field-item even"]/p/text()').extract():
text += paragraph
item['text'] = text
item['url'] = response.url
# print item['title']
yield item
...@@ -67,21 +67,20 @@ class QuotesSpider(scrapy.Spider): ...@@ -67,21 +67,20 @@ class QuotesSpider(scrapy.Spider):
request.meta['item'] = flow_info request.meta['item'] = flow_info
yield request yield request
else: elif year is None and month is None and day is None:
if year is None and month is None and day is None: self.stop_date = None
self.stop_date = None
for s in section_list:
for s in section_list: flow_info = ImportantFlowData()
flow_info = ImportantFlowData() flow_info['news_section'] = s
flow_info['news_section'] = s
request = scrapy.Request(url=self.base_url + s, callback=self.parse) request = scrapy.Request(url=self.base_url + s, callback=self.parse)
request.meta['item'] = flow_info request.meta['item'] = flow_info
yield request yield request
else: else:
print "Unable to execute this crawler with current given parameters." print "Unable to execute this crawler with current given parameters."
print "Enter all parameters: year, month and day, or none of them." print "Enter all parameters: year, month and day, or none of them."
......
...@@ -5,13 +5,15 @@ MEDIA: ...@@ -5,13 +5,15 @@ MEDIA:
Tinta Fresca, Chiapas Tinta Fresca, Chiapas
USAGE USAGE
$ cd tintaFresca $ cd tintaFresca/
------------------------------------------------------------------------------------------------------------ ------------------------------------------------------------------------------------------------------------
## Get all the news from the most current to the oldest. It's necessary to use the parse_date_files.py file ## Get all the news from the most current to the oldest. It's necessary to use the parse_date_files.py file
for the news contained in noticias.json being splitted into files by date. ## for the news contained in noticias.json being splitted into files by date. ##
$ scrapy crawl noticias --nolog -s filename=noticias.json $ scrapy crawl noticias --nolog -s filename=noticias.json
------------------------------------------------------------------------------------------------------------ ------------------------------------------------------------------------------------------------------------
## Get all the news from the most current to a specific date. ## ## Get all the news from the most current to a specific date. ##
$ scrapy crawl noticias --nolog -s filename=2018-08-30.json -a year=2018 -a month=8 -a day=30 $ scrapy crawl noticias --nolog -s filename=2018-08-30.json -a year=2018 -a month=8 -a day=30
""" """
...@@ -69,8 +71,8 @@ class QuotesSpider(scrapy.Spider): ...@@ -69,8 +71,8 @@ class QuotesSpider(scrapy.Spider):
baseURL = "http://tintafresca.com.mx/" baseURL = "http://tintafresca.com.mx/"
# section_list = ["letras_en_su_tinta/page1/", "tgz/page1/", "patria_chica/page1/", "hecho_en_chiapas/page1/", "show/page1/", "rafaga/page1/"] section_list = ["letras_en_su_tinta/page1/", "tgz/page1/", "patria_chica/page1/", "hecho_en_chiapas/page1/", "show/page1/", "rafaga/page1/"]
section_list = ["tgz/page1/", "patria_chica/page1/", "hecho_en_chiapas/page1/", "show/page1/"] # section_list = ["tgz/page1/", "patria_chica/page1/", "hecho_en_chiapas/page1/", "show/page1/"]
self.month_parser = dict(Enero='01', Febrero='02', Marzo='03', Abril='04', Mayo='05', Junio='06', self.month_parser = dict(Enero='01', Febrero='02', Marzo='03', Abril='04', Mayo='05', Junio='06',
Julio='07', Agosto='08', Septiembre='09', Octubre='10', Noviembre='11', Diciembre='12') Julio='07', Agosto='08', Septiembre='09', Octubre='10', Noviembre='11', Diciembre='12')
......
...@@ -76,7 +76,7 @@ class QuotesSpider(scrapy.Spider): ...@@ -76,7 +76,7 @@ class QuotesSpider(scrapy.Spider):
flow_info = response.meta['item'] flow_info = response.meta['item']
for link in response.css('ul.news-list').xpath('./li/h5/a/@href').extract(): for link in response.css('ul.news-list').xpath('./li/h5/a/@href').extract():
to_next_page = True flow_info['to_next_page'] = True
news_link = self.baseURL + link news_link = self.baseURL + link
yield scrapy.Request(url=news_link, callback=self.parse_item) yield scrapy.Request(url=news_link, callback=self.parse_item)
...@@ -102,7 +102,7 @@ class QuotesSpider(scrapy.Spider): ...@@ -102,7 +102,7 @@ class QuotesSpider(scrapy.Spider):
news_date = datetime(int(self.year), int(self.month), int(self.day), tzinfo=self.tz).isoformat("T") news_date = datetime(int(self.year), int(self.month), int(self.day), tzinfo=self.tz).isoformat("T")
title = response.css('div.post-title').css('h1').extract_first() title = response.css('div.post-title').css('h1').extract_first()
if title is not None : remove_tags(title) if title is not None : title = remove_tags(title)
topic = response.css('div.big-title').xpath('./h2/a/span').extract_first() topic = response.css('div.big-title').xpath('./h2/a/span').extract_first()
if topic is not None : topic = remove_tags(topic) if topic is not None : topic = remove_tags(topic)
......
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
"""
===========================================================================
THIS VERSION OF Expreso Chiapas IS NOW DEPRECATED SINCE THE SITE'S WEB PAGE
NO LONGER ALLOWS ACCES BY DAY.
THE NEW VERSION CAN BE FOUNd IN THE descarga_hacia_atras FOLDER.
===========================================================================
"""
""" """
MEDIA: MEDIA:
Expreso Chiapas, Chiapas Expreso Chiapas, Chiapas
...@@ -31,20 +19,7 @@ TAG_RE = re.compile(r'<[^>]+>') ...@@ -31,20 +19,7 @@ TAG_RE = re.compile(r'<[^>]+>')
def remove_tags(text): def remove_tags(text):
return TAG_RE.sub('', text) return TAG_RE.sub('', text)
CLEAN_RE = re.compile(r'\A.*?\sl\s') # CLEAN_RE = re.compile(r'\A.*?\sl\s')
class UTC(tzinfo):
"""
Class for Time Zone
"""
def utcoffset(self, dt):
## Time zone for Chiapas: UTC-6 ##
return timedelta(hours=-6)
def tzname(self, dt):
## Time zone name ##
return 'UTC-6'
...@@ -56,24 +31,23 @@ class QuotesSpider(scrapy.Spider): ...@@ -56,24 +31,23 @@ class QuotesSpider(scrapy.Spider):
def start_requests(self): def start_requests(self):
self.tz = UTC() year = getattr(self, "year", None)
self.year = getattr(self, "year", None) month = getattr(self, "month", None)
self.month = getattr(self, "month", None) day = getattr(self, "day", None)
self.day = getattr(self, "day", None)
self.baseURL = "http://expresochiapas.com/noticias/" + self.year + "/" + self.month.zfill(2) + "/" + self.day.zfill(2) baseURL = "http://expresochiapas.com/noticias/" + year + "/" + month.zfill(2) + "/" + day.zfill(2)
yield scrapy.Request(url=self.baseURL, callback=self.parse) yield scrapy.Request(url=baseURL, callback=self.parse)
def parse(self, response): def parse(self, response):
for link in response.xpath('//div[@class="mag-box-container"]/ul/li/a/@href').extract(): for link in response.css('div.penci-archive__list_posts').css('h2.entry-title > a::attr(href)').extract():
yield scrapy.Request(url=link, callback=self.parse_item) yield scrapy.Request(url=link, callback=self.parse_item)
nextPage = response.xpath('//div[@class="pages-nav"]/div').css('span.last-page').xpath('./a/@href').extract_first() next_page = response.css('div.nav-links').css('a.next::attr(href)').extract_first()
if nextPage is not None and nextPage != '': if next_page is not None:
yield scrapy.Request(url=nextPage, callback=self.parse) yield scrapy.Request(url=next_page, callback=self.parse)
...@@ -81,28 +55,24 @@ class QuotesSpider(scrapy.Spider): ...@@ -81,28 +55,24 @@ class QuotesSpider(scrapy.Spider):
item = NoticiasItem() item = NoticiasItem()
text = '' text = ''
try: news_date = response.css('time.entry-date::attr(datetime)').extract_first()
## this date includes time zone ##
res = response.xpath('//article[@id="the-post"]/script[@type="application/ld+json"]').extract_first()
if res is not None:
res = remove_tags(res)
jsonObj = json.loads(res)
dat = jsonObj['datePublished']
except:
dat = datetime(int(self.year), int(self.month), int(self.day), tzinfo=self.tz).isoformat("T")
item['date'] = dat
item['title'] = remove_tags(response.xpath('//div[@class="entry-header"]/h1').extract_first()).strip() title = response.css('h1.entry-title').extract_first()
if title is not None: title = remove_tags(title)
topic = response.xpath('//div[@class="entry-header"]/h5/a').extract_first() topic = response.css('div.penci-entry-categories').css('a').extract_first()
if topic is not None: if topic is not None: topic = remove_tags(topic)
item['topic'] = remove_tags(topic)
for p in response.xpath('//div[@class="entry-content entry clearfix"]/p').extract(): for p in response.css('div.penci-entry-content > p').extract():
p = p.replace("<br>", "\n")
text += remove_tags(p) + "\n" text += remove_tags(p) + "\n"
text = text.strip()
item['text'] = CLEAN_RE.sub('', text)
item['url'] = response.url
## News item info ##
item['date'] = news_date
item['title'] = title
item['topic'] = topic
item['text'] = text.strip()
item['url'] = response.url
yield item yield item
...@@ -3,7 +3,7 @@ ...@@ -3,7 +3,7 @@
# Define here the models for your scraped items # Define here the models for your scraped items
# #
# See documentation in: # See documentation in:
# http://doc.scrapy.org/en/latest/topics/items.html # https://doc.scrapy.org/en/latest/topics/items.html
import scrapy import scrapy
......
...@@ -3,7 +3,7 @@ ...@@ -3,7 +3,7 @@
# Define here the models for your spider middleware # Define here the models for your spider middleware
# #
# See documentation in: # See documentation in:
# http://doc.scrapy.org/en/latest/topics/spider-middleware.html # https://doc.scrapy.org/en/latest/topics/spider-middleware.html
from scrapy import signals from scrapy import signals
...@@ -20,14 +20,14 @@ class LajornadaSpiderMiddleware(object): ...@@ -20,14 +20,14 @@ class LajornadaSpiderMiddleware(object):
crawler.signals.connect(s.spider_opened, signal=signals.spider_opened) crawler.signals.connect(s.spider_opened, signal=signals.spider_opened)
return s return s
def process_spider_input(response, spider): def process_spider_input(self, response, spider):
# Called for each response that goes through the spider # Called for each response that goes through the spider
# middleware and into the spider. # middleware and into the spider.
# Should return None or raise an exception. # Should return None or raise an exception.
return None return None
def process_spider_output(response, result, spider): def process_spider_output(self, response, result, spider):
# Called with the results returned from the Spider, after # Called with the results returned from the Spider, after
# it has processed the response. # it has processed the response.
...@@ -35,7 +35,7 @@ class LajornadaSpiderMiddleware(object): ...@@ -35,7 +35,7 @@ class LajornadaSpiderMiddleware(object):
for i in result: for i in result:
yield i yield i
def process_spider_exception(response, exception, spider): def process_spider_exception(self, response, exception, spider):
# Called when a spider or process_spider_input() method # Called when a spider or process_spider_input() method
# (from other spider middleware) raises an exception. # (from other spider middleware) raises an exception.
...@@ -43,7 +43,7 @@ class LajornadaSpiderMiddleware(object): ...@@ -43,7 +43,7 @@ class LajornadaSpiderMiddleware(object):
# or Item objects. # or Item objects.
pass pass
def process_start_requests(start_requests, spider): def process_start_requests(self, start_requests, spider):
# Called with the start requests of the spider, and works # Called with the start requests of the spider, and works
# similarly to the process_spider_output() method, except # similarly to the process_spider_output() method, except
# that it doesn’t have a response associated. # that it doesn’t have a response associated.
...@@ -54,3 +54,50 @@ class LajornadaSpiderMiddleware(object): ...@@ -54,3 +54,50 @@ class LajornadaSpiderMiddleware(object):
def spider_opened(self, spider): def spider_opened(self, spider):
spider.logger.info('Spider opened: %s' % spider.name) spider.logger.info('Spider opened: %s' % spider.name)
class LajornadaDownloaderMiddleware(object):
# Not all methods need to be defined. If a method is not defined,
# scrapy acts as if the downloader middleware does not modify the
# passed objects.
@classmethod
def from_crawler(cls, crawler):
# This method is used by Scrapy to create your spiders.
s = cls()
crawler.signals.connect(s.spider_opened, signal=signals.spider_opened)
return s
def process_request(self, request, spider):
# Called for each request that goes through the downloader
# middleware.
# Must either:
# - return None: continue processing this request
# - or return a Response object
# - or return a Request object
# - or raise IgnoreRequest: process_exception() methods of
# installed downloader middleware will be called
return None
def process_response(self, request, response, spider):
# Called with the response returned from the downloader.
# Must either;
# - return a Response object
# - return a Request object
# - or raise IgnoreRequest
return response
def process_exception(self, request, exception, spider):
# Called when a download handler or a process_request()
# (from other downloader middleware) raises an exception.
# Must either:
# - return None: continue processing this exception
# - return a Response object: stops process_exception() chain
# - return a Request object: stops process_exception() chain
pass
def spider_opened(self, spider):
spider.logger.info('Spider opened: %s' % spider.name)
...@@ -3,7 +3,7 @@ ...@@ -3,7 +3,7 @@
# Define your item pipelines here # Define your item pipelines here
# #
# Don't forget to add your pipeline to the ITEM_PIPELINES setting # Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html # See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html
import json import json
from collections import OrderedDict from collections import OrderedDict
......
...@@ -5,9 +5,9 @@ ...@@ -5,9 +5,9 @@
# For simplicity, this file contains only settings considered important or # For simplicity, this file contains only settings considered important or
# commonly used. You can find more settings consulting the documentation: # commonly used. You can find more settings consulting the documentation:
# #
# http://doc.scrapy.org/en/latest/topics/settings.html # https://doc.scrapy.org/en/latest/topics/settings.html
# http://scrapy.readthedocs.org/en/latest/topics/downloader-middleware.html # https://doc.scrapy.org/en/latest/topics/downloader-middleware.html
# http://scrapy.readthedocs.org/en/latest/topics/spider-middleware.html # https://doc.scrapy.org/en/latest/topics/spider-middleware.html
BOT_NAME = 'laJornada' BOT_NAME = 'laJornada'
...@@ -25,7 +25,7 @@ NEWSPIDER_MODULE = 'laJornada.spiders' ...@@ -25,7 +25,7 @@ NEWSPIDER_MODULE = 'laJornada.spiders'
#CONCURRENT_REQUESTS = 32 #CONCURRENT_REQUESTS = 32
# Configure a delay for requests for the same website (default: 0) # Configure a delay for requests for the same website (default: 0)
# See http://scrapy.readthedocs.org/en/latest/topics/settings.html#download-delay # See https://doc.scrapy.org/en/latest/topics/settings.html#download-delay
# See also autothrottle settings and docs # See also autothrottle settings and docs
DOWNLOAD_DELAY = 0.5 DOWNLOAD_DELAY = 0.5
# The download delay setting will honor only one of: # The download delay setting will honor only one of:
...@@ -45,31 +45,31 @@ COOKIES_ENABLED = False ...@@ -45,31 +45,31 @@ COOKIES_ENABLED = False
#} #}
# Enable or disable spider middlewares # Enable or disable spider middlewares
# See http://scrapy.readthedocs.org/en/latest/topics/spider-middleware.html # See https://doc.scrapy.org/en/latest/topics/spider-middleware.html
#SPIDER_MIDDLEWARES = { # SPIDER_MIDDLEWARES = {
# 'laJornada.middlewares.LajornadaSpiderMiddleware': 543, # 'laJornada.middlewares.LajornadaSpiderMiddleware': 543,
#} # }
# Enable or disable downloader middlewares # Enable or disable downloader middlewares
# See http://scrapy.readthedocs.org/en/latest/topics/downloader-middleware.html # See https://doc.scrapy.org/en/latest/topics/downloader-middleware.html
#DOWNLOADER_MIDDLEWARES = { # DOWNLOADER_MIDDLEWARES = {
# 'laJornada.middlewares.MyCustomDownloaderMiddleware': 543, # 'laJornada.middlewares.LajornadaDownloaderMiddleware': 543,
#} # }
# Enable or disable extensions # Enable or disable extensions
# See http://scrapy.readthedocs.org/en/latest/topics/extensions.html # See https://doc.scrapy.org/en/latest/topics/extensions.html
#EXTENSIONS = { #EXTENSIONS = {
# 'scrapy.extensions.telnet.TelnetConsole': None, # 'scrapy.extensions.telnet.TelnetConsole': None,
#} #}
# Configure item pipelines # Configure item pipelines
# See http://scrapy.readthedocs.org/en/latest/topics/item-pipeline.html # See https://doc.scrapy.org/en/latest/topics/item-pipeline.html
ITEM_PIPELINES = { ITEM_PIPELINES = {
'laJornada.pipelines.JsonWriterPipeline': 300, 'laJornada.pipelines.JsonWriterPipeline': 300,
} }
# Enable and configure the AutoThrottle extension (disabled by default) # Enable and configure the AutoThrottle extension (disabled by default)
# See http://doc.scrapy.org/en/latest/topics/autothrottle.html # See https://doc.scrapy.org/en/latest/topics/autothrottle.html
#AUTOTHROTTLE_ENABLED = True #AUTOTHROTTLE_ENABLED = True
# The initial download delay # The initial download delay
#AUTOTHROTTLE_START_DELAY = 5 #AUTOTHROTTLE_START_DELAY = 5
...@@ -82,7 +82,7 @@ ITEM_PIPELINES = { ...@@ -82,7 +82,7 @@ ITEM_PIPELINES = {
#AUTOTHROTTLE_DEBUG = False #AUTOTHROTTLE_DEBUG = False
# Enable and configure HTTP caching (disabled by default) # Enable and configure HTTP caching (disabled by default)
# See http://scrapy.readthedocs.org/en/latest/topics/downloader-middleware.html#httpcache-middleware-settings # See https://doc.scrapy.org/en/latest/topics/downloader-middleware.html#httpcache-middleware-settings
#HTTPCACHE_ENABLED = True #HTTPCACHE_ENABLED = True
#HTTPCACHE_EXPIRATION_SECS = 0 #HTTPCACHE_EXPIRATION_SECS = 0
#HTTPCACHE_DIR = 'httpcache' #HTTPCACHE_DIR = 'httpcache'
......
# Automatically created by: scrapy startproject # Automatically created by: scrapy startproject
# #
# For more information about the [deploy] section see: # For more information about the [deploy] section see:
# https://scrapyd.readthedocs.org/en/latest/deploy.html # https://scrapyd.readthedocs.io/en/latest/deploy.html
[settings] [settings]
default = laJornada.settings default = laJornada.settings
......
...@@ -3,7 +3,7 @@ ...@@ -3,7 +3,7 @@
# Define here the models for your scraped items # Define here the models for your scraped items
# #
# See documentation in: # See documentation in:
# http://doc.scrapy.org/en/latest/topics/items.html # https://doc.scrapy.org/en/latest/topics/items.html
import scrapy import scrapy
......
...@@ -8,7 +8,7 @@ ...@@ -8,7 +8,7 @@
from scrapy import signals from scrapy import signals
class ElsalvadorSpiderMiddleware(object): class PorestoSpiderMiddleware(object):
# Not all methods need to be defined. If a method is not defined, # Not all methods need to be defined. If a method is not defined,
# scrapy acts as if the spider middleware does not modify the # scrapy acts as if the spider middleware does not modify the
# passed objects. # passed objects.
...@@ -56,7 +56,7 @@ class ElsalvadorSpiderMiddleware(object): ...@@ -56,7 +56,7 @@ class ElsalvadorSpiderMiddleware(object):
spider.logger.info('Spider opened: %s' % spider.name) spider.logger.info('Spider opened: %s' % spider.name)
class ElsalvadorDownloaderMiddleware(object): class PorestoDownloaderMiddleware(object):
# Not all methods need to be defined. If a method is not defined, # Not all methods need to be defined. If a method is not defined,
# scrapy acts as if the downloader middleware does not modify the # scrapy acts as if the downloader middleware does not modify the
# passed objects. # passed objects.
......
...@@ -3,7 +3,7 @@ ...@@ -3,7 +3,7 @@
# Define your item pipelines here # Define your item pipelines here
# #
# Don't forget to add your pipeline to the ITEM_PIPELINES setting # Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html # See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html
import json import json
from collections import OrderedDict from collections import OrderedDict
......
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
# Scrapy settings for elSalvador project # Scrapy settings for porEsto project
# #
# For simplicity, this file contains only settings considered important or # For simplicity, this file contains only settings considered important or
# commonly used. You can find more settings consulting the documentation: # commonly used. You can find more settings consulting the documentation:
...@@ -9,14 +9,14 @@ ...@@ -9,14 +9,14 @@
# https://doc.scrapy.org/en/latest/topics/downloader-middleware.html # https://doc.scrapy.org/en/latest/topics/downloader-middleware.html
# https://doc.scrapy.org/en/latest/topics/spider-middleware.html # https://doc.scrapy.org/en/latest/topics/spider-middleware.html
BOT_NAME = 'elSalvador' BOT_NAME = 'porEsto'
SPIDER_MODULES = ['elSalvador.spiders'] SPIDER_MODULES = ['porEsto.spiders']
NEWSPIDER_MODULE = 'elSalvador.spiders' NEWSPIDER_MODULE = 'porEsto.spiders'
# Crawl responsibly by identifying yourself (and your website) on the user-agent # Crawl responsibly by identifying yourself (and your website) on the user-agent
#USER_AGENT = 'elSalvador (+http://www.yourdomain.com)' #USER_AGENT = 'porEsto (+http://www.yourdomain.com)'
# Obey robots.txt rules # Obey robots.txt rules
# ROBOTSTXT_OBEY = True # ROBOTSTXT_OBEY = True
...@@ -27,7 +27,7 @@ NEWSPIDER_MODULE = 'elSalvador.spiders' ...@@ -27,7 +27,7 @@ NEWSPIDER_MODULE = 'elSalvador.spiders'
# Configure a delay for requests for the same website (default: 0) # Configure a delay for requests for the same website (default: 0)
# See https://doc.scrapy.org/en/latest/topics/settings.html#download-delay # See https://doc.scrapy.org/en/latest/topics/settings.html#download-delay
# See also autothrottle settings and docs # See also autothrottle settings and docs
DOWNLOAD_DELAY = 3 DOWNLOAD_DELAY = 0.5
# The download delay setting will honor only one of: # The download delay setting will honor only one of:
#CONCURRENT_REQUESTS_PER_DOMAIN = 16 #CONCURRENT_REQUESTS_PER_DOMAIN = 16
#CONCURRENT_REQUESTS_PER_IP = 16 #CONCURRENT_REQUESTS_PER_IP = 16
...@@ -47,13 +47,13 @@ COOKIES_ENABLED = False ...@@ -47,13 +47,13 @@ COOKIES_ENABLED = False
# Enable or disable spider middlewares # Enable or disable spider middlewares
# See https://doc.scrapy.org/en/latest/topics/spider-middleware.html # See https://doc.scrapy.org/en/latest/topics/spider-middleware.html
#SPIDER_MIDDLEWARES = { #SPIDER_MIDDLEWARES = {
# 'elSalvador.middlewares.ElsalvadorSpiderMiddleware': 543, # 'porEsto.middlewares.PorestoSpiderMiddleware': 543,
#} #}
# Enable or disable downloader middlewares # Enable or disable downloader middlewares
# See https://doc.scrapy.org/en/latest/topics/downloader-middleware.html # See https://doc.scrapy.org/en/latest/topics/downloader-middleware.html
#DOWNLOADER_MIDDLEWARES = { #DOWNLOADER_MIDDLEWARES = {
# 'elSalvador.middlewares.ElsalvadorDownloaderMiddleware': 543, # 'porEsto.middlewares.PorestoDownloaderMiddleware': 543,
#} #}
# Enable or disable extensions # Enable or disable extensions
...@@ -65,7 +65,7 @@ COOKIES_ENABLED = False ...@@ -65,7 +65,7 @@ COOKIES_ENABLED = False
# Configure item pipelines # Configure item pipelines
# See https://doc.scrapy.org/en/latest/topics/item-pipeline.html # See https://doc.scrapy.org/en/latest/topics/item-pipeline.html
ITEM_PIPELINES = { ITEM_PIPELINES = {
'elSalvador.pipelines.JsonWriterPipeline': 300, 'porEsto.pipelines.JsonWriterPipeline': 300,
} }
# Enable and configure the AutoThrottle extension (disabled by default) # Enable and configure the AutoThrottle extension (disabled by default)
......
# -*- coding: utf-8 -*-
"""
MEDIA:
Por Esto!, Yucatán
USAGE:
## Get all the news from a specific date. ##
---------------------------------------------------------------------------------------------
$ cd porEsto/
$ scrapy crawl noticias --nolog -s filename=2018-08-22.json -a year=2018 -a month=8 -a day=22
"""
import scrapy, re, json
from porEsto.items import NoticiasItem
from datetime import datetime, timedelta, tzinfo
TAG_RE = re.compile(r'<[^>]+>')
def remove_tags(text):
return TAG_RE.sub('', text)
class QuotesSpider(scrapy.Spider):
"""
Basic Scrapy Spider class
"""
name = "noticias"
def start_requests(self):
year = getattr(self, "year", None)
month = getattr(self, "month", None)
day = getattr(self, "day", None)
baseURL = "http://www.poresto.net/" + year + "/" + month.zfill(2) + "/" + day.zfill(2) + "/"
yield scrapy.Request(url=baseURL, callback=self.parse)
def parse(self, response):
for link in response.css('div.jeg_inner_content').css('h3.jeg_post_title > a::attr(href)').extract():
yield scrapy.Request(url=link, callback=self.parse_item)
next_page = response.css('div.jeg_navigation').css('a.next::attr(href)').extract_first()
if next_page is not None:
yield scrapy.Request(url=next_page, callback=self.parse)
def parse_item(self, response):
item = NoticiasItem()
text = ''
news_date = response.xpath('//meta[@property="article:published_time"]/@content').extract_first()
title = response.css('h1.jeg_post_title').extract_first()
if title is not None: title = remove_tags(title)
topic = response.css('div.jeg_meta_category > span > a').extract_first()
if topic is not None: topic = remove_tags(topic)
for p in response.css('div.entry-content').css('p').extract():
text += remove_tags(p) + "\n"
if text == '':
text = response.css('div.entry-content').css('div.content-inner').extract_first()
text.replace("<br>", '')
text = remove_tags(text)
## News item info ##
item['date'] = news_date
item['title'] = title
item['topic'] = topic
item['text'] = text.strip()
item['url'] = response.url
yield item
...@@ -4,8 +4,8 @@ ...@@ -4,8 +4,8 @@
# https://scrapyd.readthedocs.io/en/latest/deploy.html # https://scrapyd.readthedocs.io/en/latest/deploy.html
[settings] [settings]
default = elSalvador.settings default = porEsto.settings
[deploy] [deploy]
#url = http://localhost:6800/ #url = http://localhost:6800/
project = elSalvador project = porEsto
# Automatically created by: scrapy startproject
#
# For more information about the [deploy] section see:
# https://scrapyd.readthedocs.org/en/latest/deploy.html
[settings]
default = tiempoDigital.settings
[deploy]
#url = http://localhost:6800/
project = tiempoDigital
# -*- coding: utf-8 -*-
# Define here the models for your spider middleware
#
# See documentation in:
# http://doc.scrapy.org/en/latest/topics/spider-middleware.html
from scrapy import signals
class TiempodigitalSpiderMiddleware(object):
# Not all methods need to be defined. If a method is not defined,
# scrapy acts as if the spider middleware does not modify the
# passed objects.
@classmethod
def from_crawler(cls, crawler):
# This method is used by Scrapy to create your spiders.
s = cls()
crawler.signals.connect(s.spider_opened, signal=signals.spider_opened)
return s
def process_spider_input(response, spider):
# Called for each response that goes through the spider
# middleware and into the spider.
# Should return None or raise an exception.
return None
def process_spider_output(response, result, spider):
# Called with the results returned from the Spider, after
# it has processed the response.
# Must return an iterable of Request, dict or Item objects.
for i in result:
yield i
def process_spider_exception(response, exception, spider):
# Called when a spider or process_spider_input() method
# (from other spider middleware) raises an exception.
# Should return either None or an iterable of Response, dict
# or Item objects.
pass
def process_start_requests(start_requests, spider):
# Called with the start requests of the spider, and works
# similarly to the process_spider_output() method, except
# that it doesn’t have a response associated.
# Must return only requests (not items).
for r in start_requests:
yield r
def spider_opened(self, spider):
spider.logger.info('Spider opened: %s' % spider.name)
# This package will contain the spiders of your Scrapy project
#
# Please refer to the documentation for information on how to create and manage
# your spiders.
# -*- coding: utf-8 -*-
import scrapy, re
from tiempoDigital.items import NoticiasItem
"""
MEDIO:
Tiempo Digital, Oaxaca
USO:
scrapy crawl noticias --nolog -s filename=2018-02-04.json -a year=2018 -a month=2 -a day=4
"""
TAG_RE = re.compile(r'<[^>]+>')
def remove_tags(text):
return TAG_RE.sub('', text)
# LOC_RE = re.compile(r'\n.+?,? ?.+? ?\. ?- ?')
# G_RE = re.compile(r' ?- ?')
# EM_RE = re.compile(r'((Email|Correo electr.{1,3}nico|Comentarios?):\s)?[\w.-]+@[\w-]+(\.[a-zA-Z]{2,6}){1,2}\s?')
# TW_RE = re.compile(r'M.{1,3}s de la P.{1,3}lvora en Twitter: @[\w.%+-]+.', re.I)
# TW2_RE = re.compile(r'((\| )?Twitter:\s+)?(@[\w.%+-]+.)?', re.I)
# TAG2_RE = re.compile(r'\ntransition_[^\]]+\]')
# TAG3_RE = re.compile(r'\[[^\]]+[\]\n]')
class QuotesSpider(scrapy.Spider):
name = "noticias"
def start_requests(self):
year = getattr(self, "year", None)
month = getattr(self, "month", None)
day = getattr(self, "day", None)
self.baseURL = "http://tiempodigital.mx/" + year + "/" + month.zfill(2) + "/" + day.zfill(2)
yield scrapy.Request(url=self.baseURL, callback=self.parse)
def parse(self, response):
yield scrapy.Request(url=response.url, callback=self.parse_page, dont_filter=True)
pagination = response.css('div.page-nav').xpath('./a/@href').extract()
if len(pagination) > 0:
try:
pagination = pagination[-2]
except:
pagination = pagination[-1]
pagination = pagination.strip('/')
pages = int(pagination[pagination.rfind('/') + 1:])
for page in range(1, pages):
yield scrapy.Request(url=self.baseURL + '/page/' + str(page + 1), callback=self.parse_page)
def parse_page(self, response):
for post in response.xpath('//div[@class="td-ss-main-content"]').css('div.item-details'):
item = NoticiasItem()
topic = post.css('div.td-module-meta-info').xpath('./a').extract_first()
if topic is not None:
item['topic'] = remove_tags(topic)
else:
item['topic'] = None
author = post.css('div.td-module-meta-info').xpath('./span[@class="td-post-author-name"]/a').extract_first()
if author is not None:
item['author'] = remove_tags(author)
link = post.css('h3.entry-title').xpath('./a/@href').extract_first()
request = scrapy.Request(url=link, callback=self.parse_item)
request.meta['item'] = item
yield request
def parse_item(self, response):
item = response.meta['item']
text = ''
"La fecha obtenida ya incluye formato y zona horaria"
item['date'] = response.xpath('//span[@class="td-post-date"]/time/@datetime').extract_first()
item['title'] = remove_tags(response.xpath('//header[@class="td-post-title"]/h1').extract_first()).strip()
for p in response.xpath('//div[@class="td-post-content"]').css('p').extract():
text += remove_tags(p) + "\n"
# result = LOC_RE.search(text)
# if result:
# m = result.group(0)
# location = G_RE.sub('', m).strip()
# if len(location) <= 35:
# item['location'] = location
# text = text[text.find(m)+len(m):]
# text = EM_RE.sub('', text)
# text = TW_RE.sub('', text)
# text = TW2_RE.sub('', text)
# text = TAG2_RE.sub("\n", text)
# text = TAG3_RE.sub('', text)
item['text'] = text.strip()
item['url'] = response.url
yield item
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment