From f3f18db4cb9eff060823e9ac16c5a0ec12ded874 Mon Sep 17 00:00:00 2001 From: miguelpduarte Date: Sun, 17 Oct 2021 11:51:38 +0100 Subject: [PATCH 01/20] Initial commit for new scraper. Scrapy project creation --- scrape_to_csv/Dockerfile | 11 ++ scrape_to_csv/requirements.txt | 32 ++++++ scrape_to_csv/scrape_to_csv/__init__.py | 0 scrape_to_csv/scrape_to_csv/items.py | 47 ++++++++ scrape_to_csv/scrape_to_csv/middlewares.py | 103 ++++++++++++++++++ scrape_to_csv/scrape_to_csv/pipelines.py | 13 +++ scrape_to_csv/scrape_to_csv/settings.py | 88 +++++++++++++++ .../scrape_to_csv/spiders/__init__.py | 4 + scrape_to_csv/scrapy.cfg | 11 ++ 9 files changed, 309 insertions(+) create mode 100644 scrape_to_csv/Dockerfile create mode 100644 scrape_to_csv/requirements.txt create mode 100644 scrape_to_csv/scrape_to_csv/__init__.py create mode 100644 scrape_to_csv/scrape_to_csv/items.py create mode 100644 scrape_to_csv/scrape_to_csv/middlewares.py create mode 100644 scrape_to_csv/scrape_to_csv/pipelines.py create mode 100644 scrape_to_csv/scrape_to_csv/settings.py create mode 100644 scrape_to_csv/scrape_to_csv/spiders/__init__.py create mode 100644 scrape_to_csv/scrapy.cfg diff --git a/scrape_to_csv/Dockerfile b/scrape_to_csv/Dockerfile new file mode 100644 index 0000000..cfab7cf --- /dev/null +++ b/scrape_to_csv/Dockerfile @@ -0,0 +1,11 @@ +FROM python:3.9.7 + +WORKDIR /scrapper + +COPY requirements.txt . + +RUN pip install -r requirements.txt + +# Just copy the code over, instead of using volumes like before +COPY scrapy.cfg . +COPY scrape_to_csv/ scrape_to_csv/ diff --git a/scrape_to_csv/requirements.txt b/scrape_to_csv/requirements.txt new file mode 100644 index 0000000..54f799f --- /dev/null +++ b/scrape_to_csv/requirements.txt @@ -0,0 +1,32 @@ +attrs==21.2.0 +Automat==20.2.0 +cffi==1.14.6 +constantly==15.1.0 +cryptography==35.0.0 +cssselect==1.1.0 +h2==3.2.0 +hpack==3.0.0 +hyperframe==5.2.0 +hyperlink==21.0.0 +idna==3.2 +incremental==21.3.0 +itemadapter==0.4.0 +itemloaders==1.0.4 +jmespath==0.10.0 +lxml==4.6.3 +parsel==1.6.0 +priority==1.3.0 +Protego==0.1.16 +pyasn1==0.4.8 +pyasn1-modules==0.2.8 +pycparser==2.20 +PyDispatcher==2.0.5 +pyOpenSSL==21.0.0 +queuelib==1.6.2 +Scrapy==2.5.1 +service-identity==21.1.0 +six==1.16.0 +Twisted==21.7.0 +typing-extensions==3.10.0.2 +w3lib==1.22.0 +zope.interface==5.4.0 diff --git a/scrape_to_csv/scrape_to_csv/__init__.py b/scrape_to_csv/scrape_to_csv/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/scrape_to_csv/scrape_to_csv/items.py b/scrape_to_csv/scrape_to_csv/items.py new file mode 100644 index 0000000..12170d6 --- /dev/null +++ b/scrape_to_csv/scrape_to_csv/items.py @@ -0,0 +1,47 @@ +# Define here the models for your scraped items +# +# See documentation in: +# https://docs.scrapy.org/en/latest/topics/items.html +from dataclasses import dataclass, field +from typing import Optional + +# Based on the previous items.py, adaptation may be necessary + +@dataclass +class Faculty: + acronym: str + name: str + +@dataclass +class Course: + # Cannot use id and type because they are keywords in python + course_id: int + name: str + course_type: str + acronym: str + url: str # Not sure that this is useful + plan_url: str + faculty: str + year: int + +@dataclass +class CourseUnit: + course_unit_id: int + name: str + acronym: str + course_id: int + url: str + year: int + schedule_url: str + +@dataclass +class Schedule: + course_unit_id: int + lesson_type: str # T, TP, PL, etc. + day: int # 0 = monday, 1 = tuesday, .., 5 = saturday (no sunday) + duration: float # In hours. 0.5 hours is half an hour + start_time: int # TODO: Confirm data type + teacher_acronym: str # JAS, GTD, etc. + location: str # room name/number + class_name: str # 1MIEIC01 + composed_class_name: Optional[str] = field(default=None) # None or COMP_372 # TODO: See if this can be joined with the previous if it makes sense to do so diff --git a/scrape_to_csv/scrape_to_csv/middlewares.py b/scrape_to_csv/scrape_to_csv/middlewares.py new file mode 100644 index 0000000..d9e8df2 --- /dev/null +++ b/scrape_to_csv/scrape_to_csv/middlewares.py @@ -0,0 +1,103 @@ +# Define here the models for your spider middleware +# +# See documentation in: +# https://docs.scrapy.org/en/latest/topics/spider-middleware.html + +from scrapy import signals + +# useful for handling different item types with a single interface +from itemadapter import is_item, ItemAdapter + + +class ScrapeToCsvSpiderMiddleware: + # 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(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(self, response, result, spider): + # Called with the results returned from the Spider, after + # it has processed the response. + + # Must return an iterable of Request, or item objects. + for i in result: + yield i + + def process_spider_exception(self, 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 Request or item objects. + pass + + 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. + + # 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) + + +class ScrapeToCsvDownloaderMiddleware: + # 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) diff --git a/scrape_to_csv/scrape_to_csv/pipelines.py b/scrape_to_csv/scrape_to_csv/pipelines.py new file mode 100644 index 0000000..a64989e --- /dev/null +++ b/scrape_to_csv/scrape_to_csv/pipelines.py @@ -0,0 +1,13 @@ +# Define your item pipelines here +# +# Don't forget to add your pipeline to the ITEM_PIPELINES setting +# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html + + +# useful for handling different item types with a single interface +from itemadapter import ItemAdapter + + +class ScrapeToCsvPipeline: + def process_item(self, item, spider): + return item diff --git a/scrape_to_csv/scrape_to_csv/settings.py b/scrape_to_csv/scrape_to_csv/settings.py new file mode 100644 index 0000000..58e8d48 --- /dev/null +++ b/scrape_to_csv/scrape_to_csv/settings.py @@ -0,0 +1,88 @@ +# Scrapy settings for scrape_to_csv project +# +# For simplicity, this file contains only settings considered important or +# commonly used. You can find more settings consulting the documentation: +# +# https://docs.scrapy.org/en/latest/topics/settings.html +# https://docs.scrapy.org/en/latest/topics/downloader-middleware.html +# https://docs.scrapy.org/en/latest/topics/spider-middleware.html + +BOT_NAME = 'scrape_to_csv' + +SPIDER_MODULES = ['scrape_to_csv.spiders'] +NEWSPIDER_MODULE = 'scrape_to_csv.spiders' + + +# Crawl responsibly by identifying yourself (and your website) on the user-agent +#USER_AGENT = 'scrape_to_csv (+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 https://docs.scrapy.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 https://docs.scrapy.org/en/latest/topics/spider-middleware.html +#SPIDER_MIDDLEWARES = { +# 'scrape_to_csv.middlewares.ScrapeToCsvSpiderMiddleware': 543, +#} + +# Enable or disable downloader middlewares +# See https://docs.scrapy.org/en/latest/topics/downloader-middleware.html +#DOWNLOADER_MIDDLEWARES = { +# 'scrape_to_csv.middlewares.ScrapeToCsvDownloaderMiddleware': 543, +#} + +# Enable or disable extensions +# See https://docs.scrapy.org/en/latest/topics/extensions.html +#EXTENSIONS = { +# 'scrapy.extensions.telnet.TelnetConsole': None, +#} + +# Configure item pipelines +# See https://docs.scrapy.org/en/latest/topics/item-pipeline.html +#ITEM_PIPELINES = { +# 'scrape_to_csv.pipelines.ScrapeToCsvPipeline': 300, +#} + +# Enable and configure the AutoThrottle extension (disabled by default) +# See https://docs.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 https://docs.scrapy.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' diff --git a/scrape_to_csv/scrape_to_csv/spiders/__init__.py b/scrape_to_csv/scrape_to_csv/spiders/__init__.py new file mode 100644 index 0000000..ebd689a --- /dev/null +++ b/scrape_to_csv/scrape_to_csv/spiders/__init__.py @@ -0,0 +1,4 @@ +# 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. diff --git a/scrape_to_csv/scrapy.cfg b/scrape_to_csv/scrapy.cfg new file mode 100644 index 0000000..d08279f --- /dev/null +++ b/scrape_to_csv/scrapy.cfg @@ -0,0 +1,11 @@ +# Automatically created by: scrapy startproject +# +# For more information about the [deploy] section see: +# https://scrapyd.readthedocs.io/en/latest/deploy.html + +[settings] +default = scrape_to_csv.settings + +[deploy] +#url = http://localhost:6800/ +project = scrape_to_csv From 7b9a05e8665e2d08a243a292cca3186add504682 Mon Sep 17 00:00:00 2001 From: miguelpduarte Date: Sun, 17 Oct 2021 11:55:05 +0100 Subject: [PATCH 02/20] Add initial version of course and faculties spider Course spider will have to read from the faculties CSV eventually, but just focusing on selectors and structure for now. --- scrape_to_csv/.gitignore | 1 + .../scrape_to_csv/spiders/courses_spider.py | 84 +++++++++++++++++++ .../scrape_to_csv/spiders/faculties_spider.py | 20 +++++ 3 files changed, 105 insertions(+) create mode 100644 scrape_to_csv/.gitignore create mode 100644 scrape_to_csv/scrape_to_csv/spiders/courses_spider.py create mode 100644 scrape_to_csv/scrape_to_csv/spiders/faculties_spider.py diff --git a/scrape_to_csv/.gitignore b/scrape_to_csv/.gitignore new file mode 100644 index 0000000..53752db --- /dev/null +++ b/scrape_to_csv/.gitignore @@ -0,0 +1 @@ +output diff --git a/scrape_to_csv/scrape_to_csv/spiders/courses_spider.py b/scrape_to_csv/scrape_to_csv/spiders/courses_spider.py new file mode 100644 index 0000000..1097f01 --- /dev/null +++ b/scrape_to_csv/scrape_to_csv/spiders/courses_spider.py @@ -0,0 +1,84 @@ +import scrapy +from operator import itemgetter +from urllib.parse import urlparse, parse_qs + +class CoursesSpider(scrapy.Spider): + name = "courses" + allowed_domains = ["sigarra.up.pt"] + + raw_courses_url = "https://sigarra.up.pt/feup/pt/cur_geral.cur_tipo_curso_view?pv_tipo_sigla={course_type}&pv_ano_lectivo={school_year}" + + def start_requests(self): + # TODO: Get from arguments, env variables, etc, somewhere + year = 2021 + + # TODO: Get from the previous results + faculties = ['feup', 'fcup'] + + COURSE_TYPES = ['L', 'M', 'MI', 'D'] + + for faculty in faculties: + for course_type in COURSE_TYPES: + url = self.raw_courses_url.format(course_type=course_type, school_year=year) + self.logger.debug(f"Calculated url: {url}") + meta_data = {"faculty_acronym": faculty, "course_type": course_type, "year": year} + + yield scrapy.Request(url=url, callback=self.parse_course_list, meta=meta_data) + + def parse_course_list(self, response): + """ + Parses the initial course list page. + Then, issues follow-up requests to the course pages themselves to get more information. + `response.follow_all` is used since the `href`s are relative links, and the relevant elements are s + """ + + # Get the