Commit 30d91be1 authored by Renán Sosa Guillen's avatar Renán Sosa Guillen

crawlers

parent 4c9562a7
from datetime import date, datetime, timedelta, tzinfo, time
import scrapy, re import scrapy, re
from datetime import date, datetime, timedelta, tzinfo, time
from collections import OrderedDict
"""
## scrapy crawl noticias -t json --nolog -o noticias.json -a year=2017 -a month=3 -a day=22 scrapy crawl noticias -t json --nolog -o noticias.json -a year=2017 -a month=3 -a day=22
"""
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)
# re: r'(Twitter:\s+)?(@[\w.%+-]+.)?'
TW_RE = re.compile(r"""
(Twitter: # inicio de bloque, contiene la cadena 'Twitter:' (case insensitive)
\s+ # cualquier espacio (\t\n\r\f), una o mas ocurrencias
)? # fin de bloque, ninguna o una ocurrencia del bloque
(@ # inicio de bloque, contiene caracter '@'
[\w.%+-]+ # cualquier caracter alfanumerico mas los signos (.%+-), una o mas ocurrencias
. # cualquier caracter, excepto '\n'
)? # fin de bloque, ninguna o una ocurrencia del bloque
""", re.X|re.I) # banderas: verbose|case insensitive
# re: r'(Facebook|Vk):\s+[\w.%+-]+.'
FB_RE = re.compile(r"""
(Facebook|Vk) # bloque, contiene la cadena 'Facebook' o 'Vk' (case insensitive)
: # contiene el caracter ':'
\s+ # cualquier espacio (\t\n\r\f), una o mas ocurrencias
[\w.%+-]+ # cualquier caracter alfanumerico mas los signos (.%+-), una o mas ocurrencias
. # cualquier caracter, excepto '\n'
""", re.X|re.I) # banderas: verbose|case insensitive
# re: r'\(?(Foro:\s+)?(https?:\/\/)?([w{3}.])?[\w%+-]+(\.[a-zA-Z]{2,6}){1,2}[/\w.#$%&+-]*\)?.'
URL_RE = re.compile(r"""
\(? # contiene o no caracter '(', ninguna o una vez
(Foro: # inicio de bloque, contiene la cadena 'Foro:' (case insensitive)
\s+ # cualquier espacio (\t\n\r\f), una o mas ocurrencias
)? # fin de bloque, ninguna o una ocurrencia del bloque
(http # inicio de bloque, contiene cadena 'http'
s? # contiene o no caracter 's'
:\/\/ # contiene cadena '://'
)? # fin de bloque, ninguna o una ocurrencia del bloque
([w{3}.])? # el caracter 'w' tres veces y/o punto (www.), ninguna o una vez
[\w%+-]+ # cualquier caracter alfanumerico mas los signos (%+-), una o mas ocurrencias
(\. # inicio de bloque, contiene caracter '.'
[a-zA-Z]{2,6} # 2 a 6 letras, minusculas o mayusculas
){1,2} # fin de bloque, bloque se repite de 1 a 2 veces
[/\w.#$%&+-]* # seguido de '/', cualquier caracter alfanumerico mas los signos (.#$%&+-), cero o mas ocurrencias
\)? # contiene o no caracter ')', ninguna o una vez
. # cualquier caracter, excepto '\n'
""", re.X|re.I) # banderas: verbose|case insensitive
# re: r'[\w.-]+@[\w-]+(\.[a-zA-Z]{2,6}){1,2}\s?'
EMAIL_RE = re.compile(r"""
[\w.-]+ # cualquier caracter alfanumerico mas los signos (.-), una o mas repeticiones
@ # seguido de '@'
[\w-]+ # cualquier caracter alfanumerico mas el signo '-', una o mas repeticiones
(\. # inicio de bloque, contiene '.'
[a-zA-Z]{2,6} # 2 a 6 letras, minusculas o mayusculas
){1,2} # fin de bloque, bloque se repite de 1 a 2 veces
\s? # cualquier espacio (\t\n\r\f), ninguna o una coincidencia
""", re.X|re.I) # banderas: verbose|case insensitive
DIVP_RE = re.compile(r'(<div class="(credito-(autor|titulo)|hemero)">.*?<\/div>|<p class="s-s">.{,35}<\/p>|<span class="loc">.*?<\/span>)', re.S)
TRANSLATION_RE = re.compile(r'Traducci.n.*', re.I|re.S)
def clean_raw(rawText):
text = rawText.replace("* * *", '')
text = DIVP_RE.sub('', text)
text = TRANSLATION_RE.sub('', text)
return text
def text_cleaning(text):
"""
Function for cleaning news text
"""
"""
Elimina los espacios dobles, triples o mayores, innecesarios dentro del texto. Primero divide el texto de
acuerdo a los saltos de linea, despues divide cada segmento en palabras sin tomar en cuenta espacios. Luego
las palabras son agrupadas en nuevos segmentos con un solo espacio entre ellas y se agregan los saltos de
linea necesarios.
"""
newText = ''
counter = 0
text = text.replace(u'\u0164', '')
text = text.replace("Afp", '')
for segment in text.split("\n"):
counter += 1
if counter == 1:
newText += " ".join(segment.split())
elif counter > 1:
newText += "\n" + " ".join(segment.split())
"""---------------------------------------------------------------------------------------------------"""
"""
Elimina del texto la info de facebook, twitter, foro y correo electronico.
"""
newText = TW_RE.sub('', newText)
newText = FB_RE.sub('', newText)
newText = EMAIL_RE.sub('', newText)
newText = URL_RE.sub('', newText)
newText = TRANSLATION_RE.sub('', newText)
"""---------------------------------------------------------------------------------------------------"""
return newText
class UTC(tzinfo): class UTC(tzinfo):
"""clase para el 'time zone' (zona horaria)""" """clase para el 'time zone' (zona horaria)"""
def utcoffset(self, dt): def utcoffset(self, dt):
# zona horaria para centro de mexico: utc-6 # zona horaria para centro de mexico: utc-6
return timedelta(hours=-6) return timedelta(hours=-6)
def tzname(self, dt): def tzname(self, dt):
# nombre de la zona horaria # nombre de la zona horaria
return 'UTC-6' return 'UTC-6'
class NoticiasItem(scrapy.Item): class NoticiasItem(scrapy.Item):
title = scrapy.Field() title = scrapy.Field()
text = scrapy.Field() text = scrapy.Field()
date = scrapy.Field() date = scrapy.Field()
location = scrapy.Field() location = scrapy.Field()
author = scrapy.Field() author = scrapy.Field()
topic = scrapy.Field() topic = scrapy.Field()
url = scrapy.Field() url = scrapy.Field()
class QuotesSpider(scrapy.Spider): class QuotesSpider(scrapy.Spider):
name = "noticias" name = "noticias"
def start_requests(self): def start_requests(self):
self.tz = UTC() self.tz = UTC()
self.counter = 0 self.counter = 0
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)
self.baseURL='http://www.jornada.unam.mx/'+year+'/'+month.zfill(2)+'/'+day.zfill(2)+'/' self.baseURL='http://www.jornada.unam.mx/'+year+'/'+month.zfill(2)+'/'+day.zfill(2)+'/'
self.comparison_date_1 = date(2001, 12, 7) self.comparison_date_1 = date(2001, 12, 7)
self.comparison_date_2 = date(2002, 1, 8) self.comparison_date_2 = date(2002, 1, 8)
self.comparison_date_3 = date(2003, 4, 25) self.comparison_date_3 = date(2003, 4, 25)
self.comparison_date_4 = date(2004, 11, 16) self.comparison_date_4 = date(2004, 11, 16)
self.comparison_date_5 = date(2004, 12, 12) self.comparison_date_5 = date(2004, 12, 12)
self.comparison_date_6 = date(2005, 1, 31) self.comparison_date_6 = date(2005, 1, 31)
self.comparison_date_7 = date(2009, 2, 15) self.comparison_date_7 = date(2009, 2, 15)
self.date = date(int(year), int(month), int(day)) self.date = date(int(year), int(month), int(day))
# self.section_list = ['opinion', 'politica', 'economia', 'mundo', 'estados', 'ciencias', self.parse_month = {'enero': 1, 'febrero': 2, 'marzo': 3, 'abril': 4,
# 'capital', 'sociedad', 'cultura', 'espectaculos', 'deportes'] 'mayo': 5, 'junio': 6, 'julio': 7, 'agosto': 8,
'septiembre': 9, 'octubre': 10, 'noviembre': 11, 'diciembre': 12}
# for section in section_list:
# para la fecha 2009/02/15 o menores, se tiene una estructura determinada de pagina # self.section_list = ['opinion', 'politica', 'economia', 'mundo', 'estados', 'ciencias',
# para las fechas mayores a esa la estructura cambia # 'capital', 'sociedad', 'cultura', 'espectaculos', 'deportes']
# if ( requested_date <= comparison_date_1 ):
# yield scrapy.Request(url=self.baseURL+section, callback=self.parse) # for section in section_list:
# else: # para la fecha 2009/02/15 o menores, se tiene una estructura determinada de pagina
# yield scrapy.Request(url=self.baseURL+section, callback=self.parse_2) # para las fechas mayores a esa la estructura cambia
if self.date <= self.comparison_date_2: # if ( requested_date <= comparison_date_1 ):
section_list = ['index.html', 'edito.html', 'opinion.html', 'correo.html', 'politica.html', # yield scrapy.Request(url=self.baseURL+section, callback=self.parse)
'economia.html', 'cultura.html', 'espectaculos.html', 'estados.html', # else:
'capital.html', 'mundo.html', 'soc-jus.html', 'deportes.html'] # yield scrapy.Request(url=self.baseURL+section, callback=self.parse_2)
if self.date <= self.comparison_date_2:
parse_s = {'index.html': 'Portada', 'edito.html': 'Editorial', 'opinion.html': 'Opinion', section_list = ['index.html', 'edito.html', 'opinion.html', 'politica.html',
'correo.html': 'Correo', 'politica.html': 'Politica', 'economia.html': 'Economia', 'economia.html', 'cultura.html', 'espectaculos.html', 'estados.html',
'cultura.html': 'Cultura', 'espectaculos.html': 'Espectaculos', 'estados.html': 'Estados', 'capital.html', 'mundo.html', 'soc-jus.html', 'deportes.html']
'capital.html': 'Capital', 'mundo.html': 'Mundo', 'soc-jus.html': 'Sociedad',
'deportes.html': 'Deportes'} parse_s = {'index.html': 'Portada', 'edito.html': 'Editorial', 'opinion.html': 'Opinion',
'politica.html': 'Politica', 'economia.html': 'Economia',
for s in section_list: 'cultura.html': 'Cultura', 'espectaculos.html': 'Espectaculos', 'estados.html': 'Estados',
item = NoticiasItem() 'capital.html': 'Capital', 'mundo.html': 'Mundo', 'soc-jus.html': 'Sociedad',
# item['date'] = self.date 'deportes.html': 'Deportes'}
item['date'] = datetime.combine(self.date, time()).replace(tzinfo=self.tz).isoformat('T')
item['topic'] = parse_s[s] for s in section_list:
item = NoticiasItem()
if s == 'edito.html' or s == 'correo.html': # item['date'] = self.date
request = scrapy.Request(url=self.baseURL+s, callback=self.parse_item) item['date'] = datetime.combine(self.date, time()).replace(tzinfo=self.tz).isoformat('T')
else: item['topic'] = parse_s[s]
request = scrapy.Request(url=self.baseURL+s, callback=self.parse)
if s == 'edito.html':
request.meta['item'] = item request = scrapy.Request(url=self.baseURL+s, callback=self.parse_item)
yield request else:
request = scrapy.Request(url=self.baseURL+s, callback=self.parse)
elif self.date > self.comparison_date_2 and self.date <= self.comparison_date_3:
section_list = ['index.html', 'edito.html', 'opinion.html', 'correo.html', 'politica.html', request.meta['item'] = item
'economia.html', 'cultura.html', 'espectaculos.html', 'estados.html', yield request
'capital.html', 'mundo.html', 'soc-jus.html', 'deportes.html',
'index.php', 'edito.php', 'opinion.php', 'correo.php', 'politica.php', elif self.date > self.comparison_date_2 and self.date <= self.comparison_date_3:
'economia.php', 'cultura.php', 'espectaculos.php', 'estados.php', section_list = ['index.html', 'edito.html', 'opinion.html', 'politica.html',
'capital.php', 'mundo.php', 'soc-jus.php', 'deportes.php'] 'economia.html', 'cultura.html', 'espectaculos.html', 'estados.html',
'capital.html', 'mundo.html', 'soc-jus.html', 'deportes.html',
parse_s = {'index.html': 'Portada', 'edito.html': 'Editorial', 'opinion.html': 'Opinion', 'index.php', 'edito.php', 'opinion.php', 'politica.php',
'correo.html': 'Correo', 'politica.html': 'Politica', 'economia.html': 'Economia', 'economia.php', 'cultura.php', 'espectaculos.php', 'estados.php',
'cultura.html': 'Cultura', 'espectaculos.html': 'Espectaculos', 'estados.html': 'Estados', 'capital.php', 'mundo.php', 'soc-jus.php', 'deportes.php']
'capital.html': 'Capital', 'mundo.html': 'Mundo', 'soc-jus.html': 'Sociedad',
'deportes.html': 'Deportes', parse_s = {'index.html': 'Portada', 'edito.html': 'Editorial', 'opinion.html': 'Opinion',
'index.php': 'Portada', 'edito.php': 'Editorial', 'opinion.php': 'Opinion', 'politica.html': 'Politica', 'economia.html': 'Economia',
'correo.php': 'Correo', 'politica.php': 'Politica', 'economia.php': 'Economia', 'cultura.html': 'Cultura', 'espectaculos.html': 'Espectaculos', 'estados.html': 'Estados',
'cultura.php': 'Cultura', 'espectaculos.php': 'Espectaculos', 'estados.php': 'Estados', 'capital.html': 'Capital', 'mundo.html': 'Mundo', 'soc-jus.html': 'Sociedad',
'capital.php': 'Capital', 'mundo.php': 'Mundo', 'soc-jus.php': 'Sociedad', 'deportes.html': 'Deportes',
'deportes.php': 'Deportes'} 'index.php': 'Portada', 'edito.php': 'Editorial', 'opinion.php': 'Opinion',
'politica.php': 'Politica', 'economia.php': 'Economia',
for s in section_list: 'cultura.php': 'Cultura', 'espectaculos.php': 'Espectaculos', 'estados.php': 'Estados',
item = NoticiasItem() 'capital.php': 'Capital', 'mundo.php': 'Mundo', 'soc-jus.php': 'Sociedad',
# item['date'] = self.date 'deportes.php': 'Deportes'}
item['date'] = datetime.combine(self.date, time()).replace(tzinfo=self.tz).isoformat('T')
item['topic'] = parse_s[s] for s in section_list:
item = NoticiasItem()
if s == 'edito.html' or s == 'correo.html' or s == 'edito.php' or s == 'correo.php': # item['date'] = self.date
request = scrapy.Request(url=self.baseURL+s, callback=self.parse_item) item['date'] = datetime.combine(self.date, time()).replace(tzinfo=self.tz).isoformat('T')
else: item['topic'] = parse_s[s]
request = scrapy.Request(url=self.baseURL+s, callback=self.parse_2)
if s == 'edito.html' or s == 'correo.html' or s == 'edito.php' or s == 'correo.php':
request.meta['item'] = item request = scrapy.Request(url=self.baseURL+s, callback=self.parse_item)
yield request else:
request = scrapy.Request(url=self.baseURL+s, callback=self.parse_2)
elif self.date > self.comparison_date_3 and self.date <= self.comparison_date_6:
section_list = ['indexfla.php', 'edito.php', 'opinion.php', 'correo.php', 'politica.php', request.meta['item'] = item
'economia.php', 'cultura.php', 'espectaculos.php', 'estados.php', yield request
'capital.php', 'mundo.php', 'soc-jus.php', 'deportes.php', 'index.php']
elif self.date > self.comparison_date_3 and self.date <= self.comparison_date_6:
parse_s = {'indexfla.php': 'Portada', 'edito.php': 'Editorial', 'opinion.php': 'Opinion', section_list = ['indexfla.php', 'edito.php', 'opinion.php', 'correo.php', 'politica.php',
'correo.php': 'Correo', 'politica.php': 'Politica', 'economia.php': 'Economia', 'economia.php', 'cultura.php', 'espectaculos.php', 'estados.php',
'cultura.php': 'Cultura', 'espectaculos.php': 'Espectaculos', 'estados.php': 'Estados', 'capital.php', 'mundo.php', 'soc-jus.php', 'deportes.php', 'index.php']
'capital.php': 'Capital', 'mundo.php': 'Mundo', 'soc-jus.php': 'Sociedad',
'deportes.php': 'Deportes','index.php': 'Portada'} parse_s = {'indexfla.php': 'Portada', 'edito.php': 'Editorial', 'opinion.php': 'Opinion',
'correo.php': 'Correo', 'politica.php': 'Politica', 'economia.php': 'Economia',
for s in section_list: 'cultura.php': 'Cultura', 'espectaculos.php': 'Espectaculos', 'estados.php': 'Estados',
item = NoticiasItem() 'capital.php': 'Capital', 'mundo.php': 'Mundo', 'soc-jus.php': 'Sociedad',
# item['date'] = self.date 'deportes.php': 'Deportes','index.php': 'Portada'}
item['date'] = datetime.combine(self.date, time()).replace(tzinfo=self.tz).isoformat('T')
item['topic'] = parse_s[s] for s in section_list:
item = NoticiasItem()
if s == 'edito.php' or s == 'correo.php': # item['date'] = self.date
if self.date > self.comparison_date_3 and self.date <= self.comparison_date_5: item['date'] = datetime.combine(self.date, time()).replace(tzinfo=self.tz).isoformat('T')
request = scrapy.Request(url=self.baseURL+s, callback=self.parse_item) item['topic'] = parse_s[s]
elif self.date > self.comparison_date_5 and self.date <= self.comparison_date_6: if s == 'edito.php' or s == 'correo.php':
request = scrapy.Request(url=self.baseURL+s, callback=self.parse_item_2) if self.date > self.comparison_date_3 and self.date <= self.comparison_date_5:
request = scrapy.Request(url=self.baseURL+s, callback=self.parse_item)
else:
request = scrapy.Request(url=self.baseURL+s, callback=self.parse_3) elif self.date > self.comparison_date_5 and self.date <= self.comparison_date_6:
request = scrapy.Request(url=self.baseURL+s, callback=self.parse_item_2)
request.meta['item'] = item
yield request else:
request = scrapy.Request(url=self.baseURL+s, callback=self.parse_3)
elif self.date > self.comparison_date_6:
# print 'first filter' request.meta['item'] = item
section_list = ['opinion', 'politica', 'economia', 'mundo', 'estados', 'ciencias', yield request
'capital', 'sociedad', 'cultura', 'espectaculos', 'deportes']
elif self.date > self.comparison_date_6:
for s in section_list: # print 'first filter'
# para las fechas menores a 2009/02/15 y mayores a 2005/01/31, se tiene una estructura determinada de pagina section_list = ['opinion', 'politica', 'economia', 'mundo', 'estados', 'ciencias',
# para las fechas mayores a esa la estructura cambia 'capital', 'sociedad', 'cultura', 'espectaculos', 'deportes']
if self.date <= self.comparison_date_7:
yield scrapy.Request(url=self.baseURL+s, callback=self.parse_5) for s in section_list:
elif self.date > self.comparison_date_7: # para las fechas menores a 2009/02/15 y mayores a 2005/01/31, se tiene una estructura determinada de pagina
# print 'second filter in ' + self.baseURL + s # para las fechas mayores a esa la estructura cambia
yield scrapy.Request(url=self.baseURL+s, callback=self.parse_6) if self.date <= self.comparison_date_7:
yield scrapy.Request(url=self.baseURL+s, callback=self.parse_5)
elif self.date > self.comparison_date_7:
# print 'second filter in ' + self.baseURL + s
def parse(self, response): yield scrapy.Request(url=self.baseURL+s, callback=self.parse_6)
item = response.meta['item']
if self.date <= self.comparison_date_1:
if item['topic'] == 'Portada':
path = '//td[@rowspan="3"]' def parse(self, response):
else: item = response.meta['item']
if len(response.xpath('//td[@align="center"]').css('a::attr(href)').extract()) > 0: if self.date <= self.comparison_date_1:
path = '//td[@align="center"]' if item['topic'] == 'Portada':
else: path = '//td[@rowspan="3"]'
path = '//td[@align="CENTER"]' else:
if len(response.xpath('//td[@align="center"]').css('a::attr(href)').extract()) > 0:
elif self.date > self.comparison_date_1 and self.date <= self.comparison_date_2: path = '//td[@align="center"]'
if item['topic'] == 'Portada': else:
path = '//empieza' path = '//td[@align="CENTER"]'
else:
path = '//table[@bordercolor="#CCCCCC"]' elif self.date > self.comparison_date_1 and self.date <= self.comparison_date_2:
if item['topic'] == 'Portada':
for r in response.xpath(path).css('a::attr(href)').extract(): path = '//empieza'
if r[-5:] == '.html': else:
request = scrapy.Request(url=self.baseURL+r, callback=self.parse_item) path = '//table[@bordercolor="#CCCCCC"]'
request.meta['item'] = item
yield request for r in response.xpath(path).css('a::attr(href)').extract():
if r[-5:] == '.html':
request = scrapy.Request(url=self.baseURL+r, callback=self.parse_item)
request.meta['item'] = item
def parse_2(self, response): yield request
item = response.meta['item']
for r in response.xpath('//table[@bordercolor="#CCCCCC"]').css('a::attr(href)').extract():
if r[-5:] == '.html': def parse_2(self, response):
request = scrapy.Request(url=self.baseURL+r, callback=self.parse_item) item = response.meta['item']
request.meta['item'] = item
yield request for r in response.xpath('//table[@bordercolor="#CCCCCC"]').css('a::attr(href)').extract():
if r[-5:] == '.html':
request = scrapy.Request(url=self.baseURL+r, callback=self.parse_item)
request.meta['item'] = item
def parse_3(self, response): yield request
item = response.meta['item']
link_list = []
link_list.extend(response.xpath('//td[@width="100%"]').css('a::attr(href)').extract())
link_list.extend(response.xpath('//td[@width="52%"]').css('a::attr(href)').extract()) def parse_3(self, response):
link_list.extend(response.xpath('//td[@width="24%"]').css('a::attr(href)').extract()) item = response.meta['item']
link_list.extend(response.xpath('//td[@width="646"]').css('a::attr(href)').extract()) link_list = []
link_list.extend(response.xpath('//table[@width="100%"]').css('a::attr(href)').extract()) link_list.extend(response.xpath('//td[@width="100%"]').css('a::attr(href)').extract())
link_list.extend(response.xpath('//td[@width="52%"]').css('a::attr(href)').extract())
for r in link_list: link_list.extend(response.xpath('//td[@width="24%"]').css('a::attr(href)').extract())
if r[-11:] == '.html&fly=1' or r[-9:] == '.php&fly=' or r[-4:] == '.php': link_list.extend(response.xpath('//td[@width="646"]').css('a::attr(href)').extract())
if self.date > self.comparison_date_3 and self.date <= self.comparison_date_6: link_list.extend(response.xpath('//table[@width="100%"]').css('a::attr(href)').extract())
if self.date <= self.comparison_date_4:
request = scrapy.Request(url=self.baseURL+r, callback=self.parse_item) for r in link_list:
request.meta['item'] = item if r[-11:] == '.html&fly=1' or r[-9:] == '.php&fly=' or r[-4:] == '.php':
yield request if self.date > self.comparison_date_3 and self.date <= self.comparison_date_6:
if self.date <= self.comparison_date_4:
elif self.date > self.comparison_date_4 and self.date <= self.comparison_date_6: request = scrapy.Request(url=self.baseURL+r, callback=self.parse_item)
if r[:4] == 'http' and r[-4:] == '.php': request.meta['item'] = item
this_url = r.replace('\n','') yield request
if self.date <= self.comparison_date_5: elif self.date > self.comparison_date_4 and self.date <= self.comparison_date_6:
request = scrapy.Request(url=this_url, callback=self.parse_item) if r[:4] == 'http' and r[-4:] == '.php':
elif self.date > self.comparison_date_5 and self.date <= self.comparison_date_6: this_url = r.replace('\n','')
request = scrapy.Request(url=this_url, callback=self.parse_item_2)
if self.date <= self.comparison_date_5:
request.meta['item'] = item request = scrapy.Request(url=this_url, callback=self.parse_item)
yield request elif self.date > self.comparison_date_5 and self.date <= self.comparison_date_6:
request = scrapy.Request(url=this_url, callback=self.parse_item_2)
# elif self.date > self.comparison_date_5 and self.date <= self.comparison_date_6:
# request = scrapy.Request(url=self.baseURL+r, callback=self.parse_item_2) request.meta['item'] = item
# request.meta['item'] = item yield request
# yield request
# elif self.date > self.comparison_date_5 and self.date <= self.comparison_date_6:
# request = scrapy.Request(url=self.baseURL+r, callback=self.parse_item_2)
# request.meta['item'] = item
def parse_4(self, response): # yield request
print response.url
for r in response.xpath('//td[@width="646"]').css('a::attr(href)').extract():
if r[-4:] == '.php':
print r.replace('\n','') def parse_4(self, response):
# request = scrapy.Request(url=r.replace('\n',''), callback=self.parse_item) print response.url
# request.meta['item'] = item for r in response.xpath('//td[@width="646"]').css('a::attr(href)').extract():
# yield request if r[-4:] == '.php':
print r.replace('\n','')
# request = scrapy.Request(url=r.replace('\n',''), callback=self.parse_item)
# request.meta['item'] = item
def parse_5(self, response): # yield request
if ( response.url[:response.url.rfind('/')+1] == self.baseURL ): # verifica que se conserva la misma URL base
section = response.url[response.url.rfind('/')+1:]
if ( section == 'opinion' ): # la seccion 'opinion' tiene una estructura diferente a las otras
path_list = ['//*[@id="columnas"]/p/a/@href', def parse_5(self, response):
'//*[@id="opinion"]/p/a/@href'] if response.url[:response.url.rfind('/')+1] == self.baseURL: # verifica que se conserva la misma URL base
else: section = response.url[response.url.rfind('/')+1:]
path_list = ['//*[@id="article_list"]/h2/a/@href', if section == 'opinion': # la seccion 'opinion' tiene una estructura diferente a las otras
'//*[@id="article_list"]/h3/a/@href'] path_list = ['//*[@id="columnas"]/p/a/@href',
'//*[@id="opinion"]/p/a/@href']
for path in path_list: else:
for link in response.xpath(path).extract(): path_list = ['//*[@id="article_list"]/h2/a/@href',
yield scrapy.Request(url=self.baseURL+link, callback=self.parse_item_3) '//*[@id="article_list"]/h3/a/@href']
for path in path_list:
for link in response.xpath(path).extract():
def parse_6(self, response): yield scrapy.Request(url=self.baseURL+link, callback=self.parse_item_3)
if ( response.url[:response.url.rfind('/')+1] == self.baseURL ):
linkSet = set()
path_list = ['//*[@class="itemfirst"]/div/a/@href', '//*[@class="item start"]/div/a/@href',
'//*[@class="item"]/div/a/@href'] def parse_6(self, response):
if response.url[:response.url.rfind('/')+1] == self.baseURL:
for path in path_list: # linkSet = set()
for link in response.xpath(path).extract(): # path_list = ['//*[@class="itemfirst"]/div/a/@href', '//*[@class="item start"]/div/a/@href',
if link not in linkSet: # '//*[@class="item"]/div/a/@href']
linkSet.add(link) #
yield scrapy.Request(url=self.baseURL+link, callback=self.parse_item_4) # for path in path_list:
# for link in response.xpath(path).extract():
# if link not in linkSet:
# linkSet.add(link)
def parse_item(self, response): # yield scrapy.Request(url=self.baseURL+link, callback=self.parse_item_4)
item = response.meta['item'] linkSet = set()
flag = True linkLst = []
text = '' linkLst.extend(response.xpath('//*[@class="itemfirst"]/div/a/@href').extract())
try: linkLst.extend(response.xpath('//*[@class="item start"]/div/a/@href').extract())
title = response.xpath('//font[@size="5"]').extract_first() linkLst.extend(response.xpath('//*[@class="item"]/div/a/@href').extract())
item['title'] = remove_tags(title)
except: for l in linkLst:
try: link = self.baseURL + l
title = response.xpath('//p/font[@size="5"]').extract_first() if not link in linkSet:
item['title'] = remove_tags(title) linkSet.add(link)
except: yield scrapy.Request(url=link, callback=self.parse_item_4)
try:
title = response.xpath('//p/font[@size="5"]').extract()[1]
item['title'] = remove_tags(title)
except: def parse_item(self, response):
try: """
title = response.xpath('//font[@size="4"]').extract_first() FECHAS <= 2004-12-12
item['title'] = remove_tags(title) """
except: item = response.meta['item']
try: flag = True
title = response.xpath('//p/font[@size="4"]').extract_first() text = ''
item['title'] = remove_tags(title) try:
except: title = remove_tags(response.xpath('//font[@size="5"]').extract_first())
try: item['title'] = title
title = response.xpath('//p/font[@size="4"][1]').extract()[1] except:
item['title'] = remove_tags(title) try:
except: title = remove_tags(response.xpath('//p/font[@size="5"]').extract_first())
try: item['title'] = title
title = response.xpath('//font[@size="3"]').extract_first() except:
item['title'] = remove_tags(title) try:
except: title = remove_tags(response.xpath('//p/font[@size="5"]').extract()[1])
try: item['title'] = title
title = response.xpath('//p/font[@size="3"]').extract_first() except:
item['title'] = remove_tags(title) try:
except: title = remove_tags(response.xpath('//font[@size="4"]').extract_first())
try: item['title'] = title
title = response.xpath('//p/font[@size="3"][1]').extract()[1] except:
item['title'] = remove_tags(title) try:
except: title = remove_tags(response.xpath('//p/font[@size="4"]').extract_first())
try: item['title'] = title
title = response.xpath('//font[@size="+1"]').extract_first() except:
item['title'] = remove_tags(title) try:
except: title = remove_tags(response.xpath('//p/font[@size="4"][1]').extract()[1])
try: item['title'] = title
title = response.xpath('//font[@size="+0"]').extract_first() except:
item['title'] = remove_tags(title) try:
except: title = remove_tags(response.xpath('//font[@size="3"]').extract_first())
if self.date <= date(1999, 10, 3): # en esta fecha hay un cambio respecto a las otras en cuanto al html de la pag item['title'] = title
try: except:
title = remove_tags(response.xpath('//center').extract_first()) try:
item['title'] = title title = remove_tags(response.xpath('//p/font[@size="3"]').extract_first())
flag = False item['title'] = title
except: except:
pass try:
else: title = remove_tags(response.xpath('//p/font[@size="3"][1]').extract()[1])
pass item['title'] = title
except:
try:
if flag: title = remove_tags(response.xpath('//font[@size="+1"]').extract_first())
if self.date <= self.comparison_date_1: item['title'] = title
for p in response.css('p').extract(): except:
text += remove_tags(p).replace('\r','') ## no toma en cuenta los primeros indices donde esta el titulo try:
text = text.replace('\t','') title = remove_tags(response.xpath('//font[@size="+0"]').extract_first())
item['title'] = title
elif self.date > self.comparison_date_1 and self.date <= self.comparison_date_3: except:
for p in response.xpath('//table[@bordercolor="#CCCCCC"]').css('p').extract(): if self.date <= date(1999, 10, 3): # en esta fecha hay un cambio respecto a las otras en cuanto al html de la pag
text += remove_tags(p).replace('\r','') try:
text = text.replace('\t','') title = remove_tags(response.xpath('//center').extract_first())
item['title'] = title
elif self.date > self.comparison_date_3 and self.date <= self.comparison_date_4: flag = False
p = response.css('p').extract() except:
for i in range(0, len(p)): pass
text += remove_tags(p[i]).replace('\r','') else:
text = text.replace('\t','') pass
elif self.date > self.comparison_date_4 and self.date <= self.comparison_date_5:
p = response.css('p').extract() if flag:
for i in range(3, len(p)): if self.date <= self.comparison_date_1:
text += remove_tags(p[i]).replace('\r','') """
text = text.replace('\t','') FECHAS > 1999-10-03 Y FECHAS <= 2001-12-07
if text == '': """
for i in range(0, len(p)): for p in response.css('p').extract():
text += remove_tags(p[i]).replace('\r','') # text += remove_tags(p).replace('\r','') ## no toma en cuenta los primeros indices donde esta el titulo
text = text.replace('\t','') # text = text.replace('\t','')
p = clean_raw(p)
else: newsText = remove_tags(p)
text = remove_tags(response.body) text += text_cleaning(newsText)
text = text[len(title):]
m = re.search(title, text)
item['text'] = text if title[-1] == "?": text = text[m.end()+1:]
item['url'] = response.url else: text = text[m.end():]
yield item text = text.lstrip("\n")
text = text.rstrip("\n")
elif self.date > self.comparison_date_1 and self.date <= self.comparison_date_3:
def parse_item_2(self, response): """
item = response.meta['item'] FECHAS > 2001-12-07 Y FECHAS <= 2003-04-25
text = '' """
title_list = [] for p in response.xpath('//table[@bordercolor="#CCCCCC"]').css('p').extract():
title_list.extend(response.xpath('//*[@id="contenido"]/h1/text()').extract()) # text += remove_tags(p).replace('\r','')
title_list.extend(response.xpath('//h1/text()').extract()) # text = text.replace('\t','')
p = clean_raw(p)
for t in title_list: newsText = remove_tags(p)
if t is not None or t != '': text += text_cleaning(newsText)
title = remove_tags(t).replace('\r','')
title = title.replace('\t','') m = re.search(title, text)
item['title'] = title if title[-1] == "?": text = text[m.end()+1:]
else: text = text[m.end():]
p = response.css('p').extract() text = text.lstrip("\n")
for i in range(4, len(p)): text = text.rstrip("\n")
text += remove_tags(p[i]).replace('\r','')
text = text.replace('\t','') elif self.date > self.comparison_date_3 and self.date <= self.comparison_date_4:
"""
if text == '': FECHAS > 2003-04-25 Y FECHAS <= 2004-11-16
for i in range(0, len(p)): """
text += remove_tags(p[i]).replace('\r','') p = response.css('p').extract()
text = text.replace('\t','') for i in range(0, len(p)):
# text += remove_tags(p[i]).replace('\r','')
item['text'] = text # text = text.replace('\t','')
item['url'] = response.url aux = clean_raw(p[i])
yield item newsText = remove_tags(aux).lstrip("\n")
newsText = newsText.rstrip("\n")
text += text_cleaning(newsText)
def parse_item_3(self, response): elif self.date > self.comparison_date_4 and self.date <= self.comparison_date_5:
item = NoticiasItem() """
text = '' FECHAS > 2004-11-16 Y FECHAS <= 2004-12-12
# item['date'] = self.date """
item['date'] = datetime.combine(self.date, time()).replace(tzinfo=self.tz).isoformat('T') p = response.css('p').extract()
title = response.xpath('//*[@class="documentContent"]/h1[@class="title"]/text()').extract() for i in range(3, len(p)):
# text += remove_tags(p[i]).replace('\r','')
if ( len(title) > 0 ): # text = text.replace('\t','')
item['title'] = title[0] aux = clean_raw(p[i])
else: newsText = remove_tags(aux).lstrip("\n")
item['title'] = response.xpath('//*[@class="documentContent"]/h1/text()').extract_first() newsText = newsText.rstrip("\n")
text += text_cleaning(newsText)
item['topic'] = response.xpath('//*[@id="portal-breadcrumbs"]/a[2]/text()').extract_first()
for p in response.xpath('//*[@class="documentContent"]/p').extract(): if text == '':
text += remove_tags(p).replace('\r','') for i in range(0, len(p)):
text = text.replace('\t','') # text += remove_tags(p[i]).replace('\r','')
# text = text.replace('\t','')
item['text'] = text aux = clean_raw(p[i])
item['url'] = response.url newsText = remove_tags(aux).lstrip("\n")
# print item['title'] newsText = newsText.rstrip("\n")
yield item text += text_cleaning(newsText)
else:
def parse_item_4(self, response): """
item = NoticiasItem() FECHAS <= 1999-10-03
text = '' """
# path_list = ['//*[@class="col"]/p', '//*[@class="col col1"]/p', '//*[@class="col col2"]/p'] # text = remove_tags(response.body)
path_list = ['//*[@class="col"]', '//*[@class="col col1"]', '//*[@class="col col2"]'] # text = text[len(title):]
m = re.search(title, response.body)
# item['date'] = self.date body = response.body[m.end():]
item['date'] = datetime.combine(self.date, time()).replace(tzinfo=self.tz).isoformat('T') body = clean_raw(body)
item['title'] = remove_tags(response.xpath('//*[@class="cabeza"]').extract_first()) newsText = remove_tags(body).lstrip("\n")
item['topic'] = response.xpath('//*[@class="breadcrumb gui"]/span[2]/a/text()').extract_first() newsText = newsText.rstrip("\n")
text += text_cleaning(newsText)
for path in path_list:
for p in response.xpath(path).extract(): item['text'] = text
text += remove_tags(p).replace('\r','') item['url'] = response.url
text = text.replace('\t','') yield item
item['text'] = text
item['url'] = response.url
# print item['title'] def parse_item_2(self, response):
yield item """
FECHAS > 2004-12-12 Y FECHAS <= 2005-01-31
"""
item = response.meta['item']
text = ''
# titleLst = []
# titleLst.extend(response.xpath('//*[@id="contenido"]/h1/text()').extract())
# titleLst.extend(response.xpath('//h1/text()').extract())
titleSet = set()
titleSet.add(response.xpath('//*[@id="contenido"]/h1').extract_first())
titleSet.add(response.xpath('//h1').extract_first())
for t in titleSet:
if t is not None and t != '':
title = remove_tags(t).replace('\r','')
title = title.replace('\t','')
item['title'] = title
p = response.css('p').extract()
for i in range(4, len(p)):
# text += remove_tags(p[i]).replace('\r','')
# text = text.replace('\t','')
newsText = remove_tags(p[i]).lstrip("\n")
newsText = newsText.rstrip("\n")
text += text_cleaning(newsText)
if text == '':
for i in range(0, len(p)):
# text += remove_tags(p[i]).replace('\r','')
# text = text.replace('\t','')
newsText = remove_tags(p[i]).lstrip("\n")
newsText = newsText.rstrip("\n")
text += text_cleaning(newsText)
item['text'] = text
item['url'] = response.url
yield item
def parse_item_3(self, response):
"""
FECHAS > 2005-01-31 Y FECHAS <= 2009-02-15
"""
item = NoticiasItem()
text = ''
titleSet = set()
# item['date'] = self.date
item['date'] = datetime.combine(self.date, time()).replace(tzinfo=self.tz).isoformat('T')
# title = response.xpath('//*[@class="documentContent"]/h1[@class="title"]/text()').extract()
# if len(title) > 0:
# item['title'] = title[0]
# else:
# item['title'] = response.xpath('//*[@class="documentContent"]/h1/text()').extract_first()
titleSet.add(response.xpath('//*[@class="documentContent"]/h1[@class="title"]').extract_first())
titleSet.add(response.xpath('//*[@class="documentContent"]/h1').extract_first())
for t in titleSet:
if t is not None and t != '':
title = remove_tags(t).replace('\r','')
title = title.replace('\t','')
item['title'] = title
item['topic'] = response.xpath('//*[@id="portal-breadcrumbs"]/a[2]/text()').extract_first()
for p in response.xpath('//*[@class="documentContent"]/p').extract():
# text += remove_tags(p).replace('\r','')
# text = text.replace('\t','')
newsText = remove_tags(p).lstrip("\n")
newsText = newsText.rstrip("\n")
text += text_cleaning(newsText)
item['text'] = text
item['url'] = response.url
# print item['title']
yield item
def parse_item_4(self, response):
"""
FECHAS > 2009-02-15
"""
d = response.xpath('//*[@class="main-fecha"]/text()').extract_first()
d = d.replace('de', '').replace(' ', ' ').split(' ')
newsDate = date(int(d[3]), self.parse_month[d[2].lower()], int(d[1]))
if newsDate == self.date:
item = NoticiasItem()
text = ''
# path_list = ['//*[@class="col"]/p', '//*[@class="col col1"]/p', '//*[@class="col col2"]/p']
# path_list = ['//*[@class="col"]', '//*[@class="col col1"]', '//*[@class="col col2"]']
textLst = []
textLst.extend(response.xpath('//*[@class="col"]').extract())
textLst.extend(response.xpath('//*[@class="col col1"]').extract())
textLst.extend(response.xpath('//*[@class="col col2"]').extract())
# item['date'] = self.date
item['date'] = datetime.combine(newsDate, time()).replace(tzinfo=self.tz).isoformat('T')
item['title'] = remove_tags(response.xpath('//*[@class="cabeza"]').extract_first())
item['topic'] = response.xpath('//*[@class="breadcrumb gui"]/span[2]/a/text()').extract_first()
author = response.xpath('//*[@class="credito-autor"]/text()').extract_first()
if author is None or author == '':
author = response.xpath('//*[@class="credito-articulo"]/text()').extract_first()
item['author'] = author
location = remove_tags(response.xpath('//p[@class="s-s"]').extract_first())
if location is not None and location != '' and len(location) <= 35:
item['location'] = location
else:
item['location'] = None
for p in textLst:
# text += remove_tags(p).replace('\r', '')
# text = text.replace('\t', '')
p = clean_raw(p)
# newsText = remove_tags(p).lstrip("\n")
# newsText = newsText.rstrip("\n")
# text += text_cleaning(newsText)
text += remove_tags(p)
text = text.lstrip("\n")
text = text.rstrip("\n")
text = text_cleaning(text)
item['text'] = text
item['url'] = response.url
# print item['title']
# print 'title: ' + item['title'] + '\nurl: ' + item['url'] + '\n'
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