Compare commits

9 Commits
17 changed files with 52701 additions and 0 deletions
File diff suppressed because it is too large Load Diff
File diff suppressed because one or more lines are too long
+11
View File
@@ -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 = startups.settings
[deploy]
#url = http://localhost:6800/
project = startups
Binary file not shown.
+12
View File
@@ -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 StartupsItem(scrapy.Item):
# define the fields for your item here like:
# name = scrapy.Field()
pass
@@ -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 StartupsSpiderMiddleware:
# 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 StartupsDownloaderMiddleware:
# 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)
@@ -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 StartupsPipeline:
def process_item(self, item, spider):
return item
@@ -0,0 +1,93 @@
# Scrapy settings for startups 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 = "startups"
SPIDER_MODULES = ["startups.spiders"]
NEWSPIDER_MODULE = "startups.spiders"
# Crawl responsibly by identifying yourself (and your website) on the user-agent
#USER_AGENT = "startups (+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 = 0.5
# 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 = {
# "startups.middlewares.StartupsSpiderMiddleware": 543,
#}
# Enable or disable downloader middlewares
# See https://docs.scrapy.org/en/latest/topics/downloader-middleware.html
#DOWNLOADER_MIDDLEWARES = {
# "startups.middlewares.StartupsDownloaderMiddleware": 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 = {
# "startups.pipelines.StartupsPipeline": 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"
# Set settings whose default value is deprecated to a future-proof value
REQUEST_FINGERPRINTER_IMPLEMENTATION = "2.7"
TWISTED_REACTOR = "twisted.internet.asyncioreactor.AsyncioSelectorReactor"
FEED_EXPORT_ENCODING = "utf-8"
@@ -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.
@@ -0,0 +1,21 @@
import scrapy
class LinksCrawler(scrapy.Spider):
name = "startups-links"
def start_requests(self):
urls = ['https://www.eu-startups.com/directory/page/1/']
for url in urls:
yield scrapy.Request(url=url, callback=self.parse)
def parse(self, response):
links = response.selector.css("div.listing-title a::attr(href)").getall()
for link in links:
yield {
"link": link
}
next_page = response.selector.css("div.wpbdp-pagination > span.next > a::attr(href)").get()
if next_page is not None:
yield response.follow(next_page, callback=self.parse)
@@ -0,0 +1,36 @@
import scrapy
import json
class MetaDataCrawler(scrapy.Spider):
name = "startups-metadata"
def start_requests(self):
with open("links.json", "r") as file:
urls = json.load(file)
print("file loaded")
for url in urls:
yield scrapy.Request(url=url["link"], callback=self.parse)
def parse(self, response):
#name = response.selector.xpath('//div[contains(@class,"wpbdp-field-business_name")]/div[contains(@class,"value")]//text()').get()
name = response.selector.xpath('//h1[contains(@class,"entry-title")]/span//text()').get()
country = response.selector.xpath('//div[contains(@class,"wpbdp-field-category")]/div[contains(@class,"value")]//text()').get()
description_short = "".join(response.selector.xpath('//div[contains(@class,"wpbdp-field-business_description")]/div[contains(@class,"value")]//text()').extract()).strip().replace("\n", "")
description_long = "".join(response.selector.xpath('//div[contains(@class,"wpbdp-field-long_business_description")]/div[contains(@class,"value")]//text()').extract()).strip().replace("\n", "")
city = response.selector.xpath('//div[contains(@class,"wpbdp-field-based_in")]/div[contains(@class,"value")]//text()').get()
tags = response.selector.xpath('//div[contains(@class,"wpbdp-field-tags")]/div[contains(@class,"value")]//text()').get()
funding = response.selector.xpath('//div[contains(@class,"wpbdp-field-total_funding")]/div[contains(@class,"value")]//text()').get()
year = response.selector.xpath('//div[contains(@class,"wpbdp-field-founded")]/div[contains(@class,"value")]//text()').get()
website = response.selector.xpath('//div[contains(@class,"wpbdp-field-website")]/div[contains(@class,"value")]//text()').get()
yield {
"startup_name": name,
"country": country,
"description_short": description_short,
"description_long": description_long,
"city": city,
"tags": tags,
"total_funding": funding,
"year_founded": year,
"website": website
}
+245
View File
@@ -0,0 +1,245 @@
from elasticsearch import Elasticsearch
import sys
import os
import json
from datetime import datetime
import time
# elasticsearch-connection
# local
es = Elasticsearch({'host': 'localhost', 'port': 9200, 'scheme': 'https'}, basic_auth=('elastic', 'elastic'),verify_certs=False, ssl_show_warn=False)
# uni-server
# es = Elasticsearch({'host':'beta.mowesta.com', 'port': 443, 'path_prefix':'elastic', 'scheme':'https'}, basic_auth=('elastic', 'nctLD+JV+HGl+YDEmAoc'))
index_name = "startups"
# checks if elastic is up and creates the index if not already done
def check_elastic():
if not es.ping():
sys.exit("No connection to Elasticsearch")
if not es.indices.exists(index=index_name):
settings = {
"analysis": {
"analyzer": {
"searchabilityAnalyzer": {
"type": "custom",
"tokenizer": "standard",
"filter": [
"lowercase",
"asciifolding"
]
}
}
}
}
mappings = {
"properties": {
"startup_name": {
"type": "text",
"analyzer": "searchabilityAnalyzer",
"search_analyzer": "searchabilityAnalyzer",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
},
"country": {
"type": "text",
"analyzer": "searchabilityAnalyzer",
"search_analyzer": "searchabilityAnalyzer",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
},
"description_short": {
"type": "text",
"analyzer": "searchabilityAnalyzer",
"search_analyzer": "searchabilityAnalyzer",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
},
"description_long": {
"type": "text",
"analyzer": "searchabilityAnalyzer",
"search_analyzer": "searchabilityAnalyzer",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
},
"city": {
"type": "text",
"analyzer": "searchabilityAnalyzer",
"search_analyzer": "searchabilityAnalyzer",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
},
"tags": {
"type": "text",
"analyzer": "searchabilityAnalyzer",
"search_analyzer": "searchabilityAnalyzer",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
},
"total_funding": {
"type": "text",
"analyzer": "searchabilityAnalyzer",
"search_analyzer": "searchabilityAnalyzer",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
},
"year_founded": {
"type": "integer",
},
"website": {
"type": "text",
"analyzer": "searchabilityAnalyzer",
"search_analyzer": "searchabilityAnalyzer",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
},
"country_short": {
"type": "text",
"analyzer": "searchabilityAnalyzer",
"search_analyzer": "searchabilityAnalyzer",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
}
}
}
es.indices.create(index=index_name, mappings=mappings, settings=settings)
def upload(path):
with open(path, "r", encoding='utf-8') as json_file:
try:
json_loaded = json.load(json_file)
for startup in json_loaded:
time.sleep(10 / 1000)
id = str(datetime.now()).replace("-", "_").replace(" ", "_").replace(":", "_").replace(".", "_")
country_long = startup["country"]
country_short = ""
if country_long == "Austria":
country_short = "AT"
elif country_long == "Belgium":
country_short = "BE"
elif country_long == "Bulgaria":
country_short = "BG"
elif country_long == "Croatia":
country_short = "HR"
elif country_long == "Cyprus":
country_short = "CY"
elif country_long == "Czechia":
country_short = "CZ"
elif country_long == "Denmark":
country_short = "DK"
elif country_long == "Estonia":
country_short = "EE"
elif country_long == "Finland":
country_short = "FI"
elif country_long == "France":
country_short = "FR"
elif country_long == "Germany":
country_short = "DE"
elif country_long == "Greece":
country_short = "GR"
elif country_long == "Hungary":
country_short = "HU"
elif country_long == "Ireland":
country_short = "IE"
elif country_long == "Italy":
country_short = "IT"
elif country_long == "Latvia":
country_short = "LV"
elif country_long == "Lithuania":
country_short = "LT"
elif country_long == "Luxembourg":
country_short = "LU"
elif country_long == "Malta":
country_short = "MT"
elif country_long == "Netherlands":
country_short = "NL"
elif country_long == "Norway":
country_short = "NO"
elif country_long == "Poland":
country_short = "PL"
elif country_long == "Portugal":
country_short = "PT"
elif country_long == "Romania":
country_short = "RO"
elif country_long == "Slovakia":
country_short = "SK"
elif country_long == "Slovenia":
country_short = "SI"
elif country_long == "Spain":
country_short = "ES"
elif country_long == "Sweden":
country_short = "SE"
elif country_long == "Switzerland":
country_short = "CH"
elif country_long == "UK":
country_short = "GB"
else:
country_short = ""
dict = {
"startup_name": startup["startup_name"],
"country": startup["country"],
"description_short": startup["description_short"],
"description_long": startup["description_long"],
"city": startup["city"],
"tags": startup["tags"],
"total_funding": startup["total_funding"],
"year_founded": startup["year_founded"],
"website": startup["website"],
"country_short": country_short
}
es.index(index=index_name, id=id, document=dict)
except Exception as e:
print("--- Failed to upload startups.")
print(e)
# main - entry point
if __name__ == '__main__':
check_elastic()
if len(sys.argv) != 2:
sys.exit("No path given.")
upload(sys.argv[1])