commit c1ee5eba52e1e26dac93860025f30f750c4a6dac Author: Jordan ERNST Date: Thu Jul 2 08:40:13 2020 +0200 Initial commit diff --git a/ImmoScrap/__init__.py b/ImmoScrap/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/ImmoScrap/__pycache__/__init__.cpython-38.pyc b/ImmoScrap/__pycache__/__init__.cpython-38.pyc new file mode 100644 index 0000000..9aab067 Binary files /dev/null and b/ImmoScrap/__pycache__/__init__.cpython-38.pyc differ diff --git a/ImmoScrap/__pycache__/settings.cpython-38.pyc b/ImmoScrap/__pycache__/settings.cpython-38.pyc new file mode 100644 index 0000000..881dc09 Binary files /dev/null and b/ImmoScrap/__pycache__/settings.cpython-38.pyc differ diff --git a/ImmoScrap/items.py b/ImmoScrap/items.py new file mode 100644 index 0000000..0409bd3 --- /dev/null +++ b/ImmoScrap/items.py @@ -0,0 +1,12 @@ +# Define here the models for your scraped items +# +# See documentation in: +# https://docs.scrapy.org/en/latest/topics/items.html + +import scrapy + + +class ImmoscrapItem(scrapy.Item): + # define the fields for your item here like: + # name = scrapy.Field() + pass diff --git a/ImmoScrap/middlewares.py b/ImmoScrap/middlewares.py new file mode 100644 index 0000000..d771669 --- /dev/null +++ b/ImmoScrap/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 ImmoscrapSpiderMiddleware: + # 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 ImmoscrapDownloaderMiddleware: + # 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/ImmoScrap/pipelines.py b/ImmoScrap/pipelines.py new file mode 100644 index 0000000..d55da0f --- /dev/null +++ b/ImmoScrap/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 ImmoscrapPipeline: + def process_item(self, item, spider): + return item diff --git a/ImmoScrap/settings.py b/ImmoScrap/settings.py new file mode 100644 index 0000000..2202d5f --- /dev/null +++ b/ImmoScrap/settings.py @@ -0,0 +1,88 @@ +# Scrapy settings for ImmoScrap 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 = 'ImmoScrap' + +SPIDER_MODULES = ['ImmoScrap.spiders'] +NEWSPIDER_MODULE = 'ImmoScrap.spiders' + + +# Crawl responsibly by identifying yourself (and your website) on the user-agent +#USER_AGENT = 'ImmoScrap (+http://www.yourdomain.com)' + +# Obey robots.txt rules +ROBOTSTXT_OBEY = False + +# 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 = { +# 'ImmoScrap.middlewares.ImmoscrapSpiderMiddleware': 543, +#} + +# Enable or disable downloader middlewares +# See https://docs.scrapy.org/en/latest/topics/downloader-middleware.html +#DOWNLOADER_MIDDLEWARES = { +# 'ImmoScrap.middlewares.ImmoscrapDownloaderMiddleware': 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 = { +# 'ImmoScrap.pipelines.ImmoscrapPipeline': 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/ImmoScrap/spiders/Leboncoin.py b/ImmoScrap/spiders/Leboncoin.py new file mode 100644 index 0000000..dbc3d8e --- /dev/null +++ b/ImmoScrap/spiders/Leboncoin.py @@ -0,0 +1,36 @@ +import scrapy + + +filters = {"category": {"id": "9"}, + "enums": {"real_estate_type": ["1", "2", "5"], "ad_type": ["offer"]}, + "ranges": {"rooms": {}, "square": {}, "price": {"min": 0, "max": 300000}}, + "location": {"area": {"lat": 45.521971, "lng": 4.869926, "radius": 1000}, "city_zipcodes": [], "departments": [], "disable_region": False, "locations": [], "regions": []}, + "keywords": {"type": "all"}, + "owner": {}} + +data = {"pivot": "0,0,0", "limit": 100, "limit_alu": 1, + "filters": filters, + "sort_by": "time", "sort_order": "desc"} + +headers = {"User-Agent": "LBC;Android;6.0;Android SDK built for x86;phone;616a1ca77ca70180;wwan;4.30.4.0;70400;3", + "api_key": "ba0c2dad52b3ec", "Content-Type": "application/json; charset=UTF-8", "Accept-Encoding": "gzip, deflate"} + + + +class LeboncoinSpider(scrapy.Spider): + name = "leboncoin" + + def start_requests(self): + urls = [ + 'https://api.leboncoin.fr/api/adfinder/v1/search', + 'http://quotes.toscrape.com/page/2/', + ] + for url in urls: + yield scrapy.Request(url=url, callback=self.parse) + + def parse(self, response): + page = response.url.split("/")[-2] + filename = 'quotes-%s.html' % page + with open(filename, 'wb') as f: + f.write(response.body) + self.log('Saved file %s' % filename) diff --git a/ImmoScrap/spiders/Seloger.py b/ImmoScrap/spiders/Seloger.py new file mode 100644 index 0000000..80a414b --- /dev/null +++ b/ImmoScrap/spiders/Seloger.py @@ -0,0 +1,72 @@ +import scrapy +from urllib.parse import urlencode +# from math import ceil + +# The only requrement to bypass protections on seloger is to spoof User-Agent + + +class SelogerSpider(scrapy.Spider): + name = "seloger" + + baseurl = 'https://www.seloger.com/list.htm' + vienne_area = r'uyztGgtx\zLeTdNcPvb@iJpFi@tDLdHtAbNxI|LvJx`@zi@|@bB|Eld@p@jNg@xn@gApPwBzR_FlVcBhEkDdBaDZgLeB{Aw@mwBi}BmBwAaEwEeAsBI}CxNij@' + stetienne_area = r'}mktGwtwYp@aClDsF`CaHpA_HfFgFlPkIjc@{HjDsBtK?dm@eKxIx@bCbBtDdKRpC}@`GTjIgArGcC`G{@jEyH`L{AbGcCrBmBjDuQ~L_EjDsFvA{G|C_Rx@mBj@eHh@gTN}Ey@oHoC_KkNuE}Cg@mDScGReK' + params = {'projects': '2,5', + 'types': '1,2,12,11', + 'natures': '1', + 'price': 'NaN/300000', + 'sort': 'd_dt_crea', + 'enterprise': 0, + 'qsVersion': 1.0, + 'LISTING-LISTpg': 1} + vienne_params = params.copy() + vienne_params['searchareas'] = vienne_area + stetienne_params = params.copy() + stetienne_params['searchareas'] = stetienne_area + + headers = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:78.0) Gecko/20100101 Firefox/78.0'} + + pagination_xpath = '//div[has-class("ckWPHD")]//text()' + ads_css_sel = '.ListContent__SmartClassifiedExtended-sc-1viyr2k-2' + url_css_sel = '.dXJclF::attr(href)' + type_css_sel = '.joPkKZ::text' + price_css_sel = '.mVWFG::text' + infos_css_sel = ".eJYQQA" # Contains Rooms, bedrooms, area + + def start_requests(self): + urls = [ + f'{self.baseurl}?{urlencode(self.vienne_params)},' + f'{self.baseurl}?{urlencode(self.stetienne_params)}' + ] + for url in urls: + yield scrapy.Request(url=url, headers=self.headers, callback=self.parse) + + def parse(self, response): + ads = response.css(self.ads_css_sel) + for ad in ads: + infos = ad.css(self.infos_css_sel) + + yield { + 'url': ad.css(self.url_css_sel).get().split('?')[0], + 'type': ad.css(self.type_css_sel).get(), + 'price': ad.css(self.price_css_sel).get().replace('\xa0', ' '), + 'rooms': infos.xpath('./li[contains(., "p")]/text()').get(), + 'bedrooms': infos.xpath('./li[contains(., "ch")]/text()').get(), + 'area': infos.xpath('./li[contains(., "m²")]/text()').get() + } + """ + pricefloat = float(price.replace(',', '.').replace(' ', '').replace('€', '')) + areafloat = float(area.replace(',', '.').replace(' ', '').replace('m²', '')) + pricesqmint = round(pricefloat / areafloat) + print(url, type, price, rooms, bedrooms, area, pricesqmint) + """ + active_page = response.url + active_page_nb = int(active_page.split('LISTING-LISTpg=')[1]) + + current_ads_nb = response.xpath(self.pagination_xpath).getall()[4] + total_ads_nb = response.xpath(self.pagination_xpath).getall()[-1] + + if current_ads_nb != total_ads_nb: # If not last page + next_page_nb = active_page_nb + 1 + next_page = active_page.split('LISTING-LISTpg=')[0] + f'LISTING-LISTpg={next_page_nb}' + yield response.follow(next_page, headers=self.headers, callback=self.parse) diff --git a/ImmoScrap/spiders/__init__.py b/ImmoScrap/spiders/__init__.py new file mode 100644 index 0000000..ebd689a --- /dev/null +++ b/ImmoScrap/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/scrapy.cfg b/scrapy.cfg new file mode 100644 index 0000000..4fce3f1 --- /dev/null +++ b/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 = ImmoScrap.settings + +[deploy] +#url = http://localhost:6800/ +project = ImmoScrap