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

crawlers

parent 30b928b1
......@@ -5,13 +5,15 @@ MEDIA:
Diario de Chiapas, Chiapas
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
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=2018-08-30.json -a year=2018 -a month=8 -a day=30
"""
......
......@@ -3,7 +3,7 @@
# Define here the models for your scraped items
#
# See documentation in:
# http://doc.scrapy.org/en/latest/topics/items.html
# https://doc.scrapy.org/en/latest/topics/items.html
import scrapy
......
......@@ -3,7 +3,7 @@
# Define here the models for your spider middleware
#
# 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
......@@ -20,14 +20,14 @@ class PrensahnSpiderMiddleware(object):
crawler.signals.connect(s.spider_opened, signal=signals.spider_opened)
return s
def process_spider_input(response, spider):
def process_spider_input(self, 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):
def process_spider_output(self, response, result, spider):
# Called with the results returned from the Spider, after
# it has processed the response.
......@@ -35,7 +35,7 @@ class PrensahnSpiderMiddleware(object):
for i in result:
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
# (from other spider middleware) raises an exception.
......@@ -43,7 +43,7 @@ class PrensahnSpiderMiddleware(object):
# or Item objects.
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
# similarly to the process_spider_output() method, except
# that it doesn’t have a response associated.
......@@ -54,3 +54,50 @@ class PrensahnSpiderMiddleware(object):
def spider_opened(self, spider):
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 @@
# 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
# See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html
import json
from collections import OrderedDict
......
......@@ -5,9 +5,9 @@
# 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
# https://doc.scrapy.org/en/latest/topics/settings.html
# https://doc.scrapy.org/en/latest/topics/downloader-middleware.html
# https://doc.scrapy.org/en/latest/topics/spider-middleware.html
BOT_NAME = 'prensaHn'
......@@ -25,7 +25,7 @@ NEWSPIDER_MODULE = 'prensaHn.spiders'
#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 https://doc.scrapy.org/en/latest/topics/settings.html#download-delay
# See also autothrottle settings and docs
DOWNLOAD_DELAY = 0.5
# The download delay setting will honor only one of:
......@@ -45,31 +45,31 @@ COOKIES_ENABLED = False
#}
# 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 = {
# 'prensaHn.middlewares.PrensahnSpiderMiddleware': 543,
#}
# 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 = {
# 'prensaHn.middlewares.MyCustomDownloaderMiddleware': 543,
# 'prensaHn.middlewares.PrensahnDownloaderMiddleware': 543,
#}
# 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 = {
# 'scrapy.extensions.telnet.TelnetConsole': None,
#}
# 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 = {
'prensaHn.pipelines.JsonWriterPipeline': 300,
}
# 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
# The initial download delay
#AUTOTHROTTLE_START_DELAY = 5
......@@ -82,7 +82,7 @@ ITEM_PIPELINES = {
#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
# See https://doc.scrapy.org/en/latest/topics/downloader-middleware.html#httpcache-middleware-settings
#HTTPCACHE_ENABLED = True
#HTTPCACHE_EXPIRATION_SECS = 0
#HTTPCACHE_DIR = 'httpcache'
......
# -*- 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
from datetime import datetime, date
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'<[^>]+>')
def remove_tags(text):
return TAG_RE.sub('', text)
class ImportantData(scrapy.Item):
CONTINUE_SEARCHING = scrapy.Field()
LAST_LINK = scrapy.Field()
page = scrapy.Field()
section_url = scrapy.Field()
url = scrapy.Field()
class ImportantFlowData(scrapy.Item):
"""
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()
return_url = scrapy.Field()
class QuotesSpider(scrapy.Spider):
"""
Basic Scrapy Spider class
"""
name = "noticias"
def start_requests(self):
year = getattr(self, "year", None)
year = getattr(self, "year", None)
month = getattr(self, "month", None)
day = getattr(self, "day", None)
day = getattr(self, "day", 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))
else:
self.stopDate = None
base_url = "http://www.laprensa.hn/"
section_list = ["economia", "mundo", "tecnologia", "cine", "cultura", "turismo",
"honduras", "sucesos", "espectaculos", "deportes"]
baseURL = "http://www.laprensa.hn/"
if year is not None and month is not None and day is not None:
self.stop_date = date(int(year), int(month), int(day))
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 + "/"
request = scrapy.Request(url=base_url + s, callback=self.parse_with_stop_date)
request.meta['item'] = flow_info
yield request
sectionList = ["economia", "mundo", "tecnologia", "cine", "cultura", "turismo",
"honduras", "sucesos", "espectaculos", "deportes"]
# sectionList = ["economia"]
elif year is None and month is None and day is None:
for s in section_list:
flow_info = ImportantFlowData()
flow_info['news_section'] = s
flow_info['section_url'] = base_url + s + "/"
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
request = scrapy.Request(url=base_url + s, callback=self.parse)
request.meta['item'] = flow_info
yield request
else:
for s in sectionList:
info = ImportantData()
info['page'] = 1
info['CONTINUE_SEARCHING'] = False
request = scrapy.Request(url=baseURL + s, callback=self.parse_with_stop_date)
request.meta['item'] = info
yield request
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:
linkSet = set(response.css('article.grid').css('div.content').css('a::attr(href)').extract())
try:
linkSet.remove(searchData['section_url'])
except KeyError:
CONTINUE_SEARCHING = False
section = response.xpath('//div[@id="section_title"]/h1/a').extract_first()
if section is not None : section = remove_tags(section)
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)
if CONTINUE_SEARCHING:
searchData['page'] += 1
page = searchData['page']
url = searchData['section_url']
request = scrapy.Request(url=url + "?page=" + str(page), callback=self.parse)
request.meta['item'] = searchData
next_page = response.xpath('//ul[@id="paginacion"]').css('span.next > a::attr(href)').extract_first()
if next_page is not None:
flow_info = ImportantFlowData()
flow_info['news_section'] = news_section
flow_info['section_url'] = section_url
request = scrapy.Request(url=section_url + next_page, callback=self.parse)
request.meta['item'] = flow_info
yield request
def parse_with_stop_date(self, response):
searchData = response.meta['item']
CONTINUE_SEARCHING = searchData['CONTINUE_SEARCHING']
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)
flow_info = response.meta['item']
news_section = flow_info['news_section']
section_url = flow_info['section_url']
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:
linkSet = set(response.css('article.grid').css('div.content').css('a::attr(href)').extract())
try:
linkSet.remove(searchData['section_url'])
linkList = list(linkSet)
except KeyError:
linkList = []
for link in linkList:
info = ImportantData()
info['url'] = response.url
info['page'] = searchData['page']
info['section_url'] = searchData['section_url']
if link == linkList[-1]: info['LAST_LINK'] = True
else: info['LAST_LINK'] = False
reqst = scrapy.Request(url=link, callback=self.parse_item_with_stop_date)
reqst.meta['item'] = info
yield reqst
section = response.xpath('//div[@id="section_title"]/h1/a').extract_first()
if section is not None : section = remove_tags(section)
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:
flow_info = ImportantFlowData()
flow_info['news_section'] = news_section
flow_info['section_url'] = section_url
flow_info['return_url'] = response.url
if link_list.index(link) == link_list.index(link_list[-1]):
flow_info['is_last_link'] = True
else:
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:
searchData['CONTINUE_SEARCHING'] = False
searchData['page'] += 1
page = searchData['page']
url = searchData['section_url']
request = scrapy.Request(url=url + "?page=" + str(page), callback=self.parse_with_stop_date)
request.meta['item'] = searchData
yield request
next_page = response.xpath('//ul[@id="paginacion"]').css('span.next > a::attr(href)').extract_first()
if next_page is not None:
flow_info = ImportantFlowData()
flow_info['to_next_page'] = False
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
def parse_item(self, response):
item = NoticiasItem()
res = remove_tags(response.xpath('//script[@type="application/ld+json"]').extract_first())
newsData = json.loads(res)
item['date'] = newsData['datePublished'][:-1]
item['title'] = newsData['headline']
resp = remove_tags(response.xpath('//script[@type="application/ld+json"]').extract_first())
news_data = json.loads(resp)
try:
topic = newsData['articleSection']
topic = news_data['articleSection']
except:
topic = None
item['topic'] = topic
item['text'] = newsData['articleBody']
item['url'] = response.url
## 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
yield item
def parse_item_with_stop_date(self, response):
res = remove_tags(response.xpath('//script[@type="application/ld+json"]').extract_first())
newsData = json.loads(res)
d = newsData['datePublished']
d = d[:d.find("T")]
dt = datetime.strptime(d, '%Y-%m-%d').date()
if dt >= self.stopDate:
info = response.meta['item']
resp = remove_tags(response.xpath('//script[@type="application/ld+json"]').extract_first())
news_data = json.loads(resp)
news_date = news_data['datePublished']
news_date = news_date[:news_date.find("T")]
news_date = datetime.strptime(news_date, '%Y-%m-%d').date()
if news_date >= self.stop_date:
flow_info = response.meta['item']
item = NoticiasItem()
text = ''
item['date'] = newsData['datePublished'][:-1]
item['title'] = newsData['headline']
try:
topic = newsData['articleSection']
topic = news_data['articleSection']
except:
topic = None
item['topic'] = topic
item['text'] = newsData['articleBody']
item['url'] = response.url
## 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
yield item
if info['LAST_LINK']:
info['CONTINUE_SEARCHING'] = True
request = scrapy.Request(url=info['url'], callback=self.parse_with_stop_date, dont_filter=True)
request.meta['item'] = info
if flow_info['is_last_link']:
flow_info['to_next_page'] = True
request = scrapy.Request(url=flow_info['return_url'], callback=self.parse_with_stop_date, dont_filter=True)
request.meta['item'] = flow_info
yield request
# Automatically created by: scrapy startproject
#
# 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]
default = prensaHn.settings
......
......@@ -5,13 +5,15 @@ MEDIA:
El Heraldo de Chihuahua, Chihuahua
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
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=2018-08-30.json -a year=2018 -a month=8 -a day=30
"""
......
......@@ -67,21 +67,20 @@ class QuotesSpider(scrapy.Spider):
request.meta['item'] = flow_info
yield request
else:
if year is None and month is None and day is None:
self.stop_date = None
for s in section_list:
flow_info = ImportantFlowData()
flow_info['news_section'] = s
elif year is None and month is None and day is None:
self.stop_date = None
for s in section_list:
flow_info = ImportantFlowData()
flow_info['news_section'] = s
request = scrapy.Request(url=self.base_url + s, callback=self.parse)
request.meta['item'] = flow_info
yield request
request = scrapy.Request(url=self.base_url + s, callback=self.parse)
request.meta['item'] = flow_info
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."
else:
print "Unable to execute this crawler with current given parameters."
print "Enter all parameters: year, month and day, or none of them."
......
......@@ -5,13 +5,15 @@ MEDIA:
Tinta Fresca, Chiapas
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
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=2018-08-30.json -a year=2018 -a month=8 -a day=30
"""
......@@ -69,8 +71,8 @@ class QuotesSpider(scrapy.Spider):
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 = ["tgz/page1/", "patria_chica/page1/", "hecho_en_chiapas/page1/", "show/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/"]
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')
......
......@@ -76,7 +76,7 @@ class QuotesSpider(scrapy.Spider):
flow_info = response.meta['item']
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
yield scrapy.Request(url=news_link, callback=self.parse_item)
......@@ -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")
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()
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