Commit 9fd0391f authored by Renán Sosa Guillen's avatar Renán Sosa Guillen

crawlers

parent 30b928b1
...@@ -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'
......
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
"""
MEDIA:
La Prensa, Honduras
USAGE:
$ cd prensaHn/
------------------------------------------------------------------------------------------------------------
## 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. ##
$ scrapy crawl noticias --nolog -s filename=noticias.json
------------------------------------------------------------------------------------------------------------
## Get all the news from the most current to a specific date. ##
scrapy crawl noticias --nolog -s filename=noticias.json -a year=2018 -a month=3 -a day=7
"""
import scrapy, re, json import scrapy, re, json
from datetime import datetime, date from datetime import datetime, date
from prensaHn.items import NoticiasItem from prensaHn.items import NoticiasItem
"""
MEDIO:
La Prensa, Honduras
USO:
// Si se quiere obtener todas las noticias desde las más actuales hasta las más antiguas. //
scrapy crawl noticias --nolog -s filename=noticias.json
-------------------------------------------------------------------------------------------------
// Si se quiere obtener todas las noticias desde las más actuales hasta una fecha específica. //
scrapy crawl noticias --nolog -s filename=noticias.json -a year=2018 -a month=3 -a day=7
-------------------------------------------------------------------------------------------------
Después será necesario hacer uso del archivo parse_date_files.py para que las noticias contenidas
en noticias.json sean separadas en archivos por fecha.
"""
TAG_RE = re.compile(r'<[^>]+>') TAG_RE = re.compile(r'<[^>]+>')
def remove_tags(text): def remove_tags(text):
return TAG_RE.sub('', text) return TAG_RE.sub('', text)
class ImportantData(scrapy.Item):
CONTINUE_SEARCHING = scrapy.Field() class ImportantFlowData(scrapy.Item):
LAST_LINK = scrapy.Field() """
page = scrapy.Field() Useful data for the flow of the implementation
"""
to_next_page = scrapy.Field()
is_last_link = scrapy.Field()
news_section = scrapy.Field()
section_url = scrapy.Field() section_url = scrapy.Field()
url = scrapy.Field() return_url = scrapy.Field()
class QuotesSpider(scrapy.Spider): class QuotesSpider(scrapy.Spider):
"""
Basic Scrapy Spider class
"""
name = "noticias" name = "noticias"
def start_requests(self): def start_requests(self):
year = getattr(self, "year", None) year = getattr(self, "year", None)
month = getattr(self, "month", None) month = getattr(self, "month", None)
day = getattr(self, "day", None) day = getattr(self, "day", None)
base_url = "http://www.laprensa.hn/"
section_list = ["economia", "mundo", "tecnologia", "cine", "cultura", "turismo",
"honduras", "sucesos", "espectaculos", "deportes"]
if year is not None and month is not None and day is not None: if year is not None and month is not None and day is not None:
self.stopDate = date(int(year), int(month), int(day)) self.stop_date = date(int(year), int(month), int(day))
else:
self.stopDate = None
baseURL = "http://www.laprensa.hn/" for s in section_list:
flow_info = ImportantFlowData()
flow_info['to_next_page'] = False
flow_info['news_section'] = s
flow_info['section_url'] = base_url + s + "/"
sectionList = ["economia", "mundo", "tecnologia", "cine", "cultura", "turismo", request = scrapy.Request(url=base_url + s, callback=self.parse_with_stop_date)
"honduras", "sucesos", "espectaculos", "deportes"] request.meta['item'] = flow_info
# sectionList = ["economia"]
if self.stopDate is None:
for s in sectionList:
info = ImportantData()
info['page'] = 1
request = scrapy.Request(url=baseURL + s, callback=self.parse)
request.meta['item'] = info
yield request yield request
else: elif year is None and month is None and day is None:
for s in sectionList: for s in section_list:
info = ImportantData() flow_info = ImportantFlowData()
info['page'] = 1 flow_info['news_section'] = s
info['CONTINUE_SEARCHING'] = False flow_info['section_url'] = base_url + s + "/"
request = scrapy.Request(url=baseURL + s, callback=self.parse_with_stop_date)
request.meta['item'] = info request = scrapy.Request(url=base_url + s, callback=self.parse)
request.meta['item'] = flow_info
yield request yield request
else:
print "Unable to execute this crawler with current given parameters."
print "Enter all parameters: year, month and day, or none of them."
def parse(self, response):
searchData = response.meta['item']
CONTINUE_SEARCHING = True
if searchData['page'] == 1:
searchData['section_url'] = response.url + "/"
entrySet = set(response.css('article.entry').css('div.content').css('a::attr(href)').extract())
entrySet.remove(searchData['section_url'])
linkSet = set(response.css('article.grid').css('div.content').css('a::attr(href)').extract())
linkSet.remove(searchData['section_url'])
linkSet.union(entrySet)
def parse(self, response):
flow_info = response.meta['item']
news_section = flow_info['news_section']
section_url = flow_info['section_url']
link_list = []
if news_section == "deportes":
section = news_section.capitalize()
elif news_section == "espectaculos":
section = u'Expect\xc3\xa1culos'
else: else:
linkSet = set(response.css('article.grid').css('div.content').css('a::attr(href)').extract()) section = response.xpath('//div[@id="section_title"]/h1/a').extract_first()
try: if section is not None : section = remove_tags(section)
linkSet.remove(searchData['section_url'])
except KeyError:
CONTINUE_SEARCHING = False
for link in linkSet: for entry in response.css('article.grid').css('div.content'):
if section in entry.css('a.category').extract_first():
link_list.append(entry.xpath('./a[2]/@href').extract_first())
for link in link_list:
yield scrapy.Request(url=link, callback=self.parse_item) yield scrapy.Request(url=link, callback=self.parse_item)
if CONTINUE_SEARCHING: next_page = response.xpath('//ul[@id="paginacion"]').css('span.next > a::attr(href)').extract_first()
searchData['page'] += 1 if next_page is not None:
page = searchData['page'] flow_info = ImportantFlowData()
url = searchData['section_url'] flow_info['news_section'] = news_section
request = scrapy.Request(url=url + "?page=" + str(page), callback=self.parse) flow_info['section_url'] = section_url
request.meta['item'] = searchData
request = scrapy.Request(url=section_url + next_page, callback=self.parse)
request.meta['item'] = flow_info
yield request yield request
def parse_with_stop_date(self, response): def parse_with_stop_date(self, response):
searchData = response.meta['item'] flow_info = response.meta['item']
CONTINUE_SEARCHING = searchData['CONTINUE_SEARCHING'] news_section = flow_info['news_section']
section_url = flow_info['section_url']
if not CONTINUE_SEARCHING:
if searchData['page'] == 1:
searchData['section_url'] = response.url + "/"
entrySet = set(response.css('article.entry').css('div.content').css('a::attr(href)').extract())
entrySet.remove(searchData['section_url'])
linkSet = set(response.css('article.grid').css('div.content').css('a::attr(href)').extract())
linkSet.remove(searchData['section_url'])
linkSet.union(entrySet)
linkList = list(linkSet)
if not flow_info['to_next_page']:
link_list = []
if news_section == "deportes":
section = news_section.capitalize()
elif news_section == "espectaculos":
section = u'Expect\xc3\xa1culos'
else: else:
linkSet = set(response.css('article.grid').css('div.content').css('a::attr(href)').extract()) section = response.xpath('//div[@id="section_title"]/h1/a').extract_first()
try: if section is not None : section = remove_tags(section)
linkSet.remove(searchData['section_url'])
linkList = list(linkSet) for entry in response.css('article.grid').css('div.content'):
except KeyError: if section in entry.css('a.category').extract_first():
linkList = [] link_list.append(entry.xpath('./a[2]/@href').extract_first())
for link in linkList: for link in link_list:
info = ImportantData() flow_info = ImportantFlowData()
info['url'] = response.url flow_info['news_section'] = news_section
info['page'] = searchData['page'] flow_info['section_url'] = section_url
info['section_url'] = searchData['section_url'] flow_info['return_url'] = response.url
if link == linkList[-1]: info['LAST_LINK'] = True
else: info['LAST_LINK'] = False if link_list.index(link) == link_list.index(link_list[-1]):
reqst = scrapy.Request(url=link, callback=self.parse_item_with_stop_date) flow_info['is_last_link'] = True
reqst.meta['item'] = info else:
yield reqst flow_info['is_last_link'] = False
request = scrapy.Request(url=link, callback=self.parse_item_with_stop_date)
request.meta['item'] = flow_info
yield request
else: else:
searchData['CONTINUE_SEARCHING'] = False next_page = response.xpath('//ul[@id="paginacion"]').css('span.next > a::attr(href)').extract_first()
searchData['page'] += 1
page = searchData['page'] if next_page is not None:
url = searchData['section_url'] flow_info = ImportantFlowData()
request = scrapy.Request(url=url + "?page=" + str(page), callback=self.parse_with_stop_date) flow_info['to_next_page'] = False
request.meta['item'] = searchData flow_info['news_section'] = news_section
flow_info['section_url'] = section_url
request = scrapy.Request(url=section_url + next_page, callback=self.parse_with_stop_date)
request.meta['item'] = flow_info
yield request yield request
def parse_item(self, response): def parse_item(self, response):
item = NoticiasItem() item = NoticiasItem()
res = remove_tags(response.xpath('//script[@type="application/ld+json"]').extract_first()) resp = remove_tags(response.xpath('//script[@type="application/ld+json"]').extract_first())
newsData = json.loads(res) news_data = json.loads(resp)
item['date'] = newsData['datePublished'][:-1]
item['title'] = newsData['headline']
try: try:
topic = newsData['articleSection'] topic = news_data['articleSection']
except: except:
topic = None topic = None
item['topic'] = topic
item['text'] = newsData['articleBody']
## News item info ##
item['date'] = news_data['datePublished'][:-1]
item['title'] = news_data['headline']
item['topic'] = topic
item['text'] = news_data['articleBody']
item['url'] = response.url item['url'] = response.url
yield item yield item
def parse_item_with_stop_date(self, response): def parse_item_with_stop_date(self, response):
res = remove_tags(response.xpath('//script[@type="application/ld+json"]').extract_first()) resp = remove_tags(response.xpath('//script[@type="application/ld+json"]').extract_first())
newsData = json.loads(res) news_data = json.loads(resp)
d = newsData['datePublished'] news_date = news_data['datePublished']
d = d[:d.find("T")] news_date = news_date[:news_date.find("T")]
dt = datetime.strptime(d, '%Y-%m-%d').date() news_date = datetime.strptime(news_date, '%Y-%m-%d').date()
if dt >= self.stopDate: if news_date >= self.stop_date:
info = response.meta['item'] flow_info = response.meta['item']
item = NoticiasItem() item = NoticiasItem()
text = ''
item['date'] = newsData['datePublished'][:-1]
item['title'] = newsData['headline']
try: try:
topic = newsData['articleSection'] topic = news_data['articleSection']
except: except:
topic = None topic = None
item['topic'] = topic
item['text'] = newsData['articleBody']
## News item info ##
item['date'] = news_data['datePublished'][:-1]
item['title'] = news_data['headline']
item['topic'] = topic
item['text'] = news_data['articleBody']
item['url'] = response.url item['url'] = response.url
yield item yield item
if info['LAST_LINK']: if flow_info['is_last_link']:
info['CONTINUE_SEARCHING'] = True flow_info['to_next_page'] = True
request = scrapy.Request(url=info['url'], callback=self.parse_with_stop_date, dont_filter=True)
request.meta['item'] = info request = scrapy.Request(url=flow_info['return_url'], callback=self.parse_with_stop_date, dont_filter=True)
request.meta['item'] = flow_info
yield request yield request
# 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
""" """
......
...@@ -67,8 +67,7 @@ class QuotesSpider(scrapy.Spider): ...@@ -67,8 +67,7 @@ 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:
......
...@@ -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)
......
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