477 lines
16 KiB
Python
477 lines
16 KiB
Python
import scrapy
|
|
from configparser import ConfigParser
|
|
import os
|
|
import pandas as pd
|
|
import logging
|
|
|
|
|
|
|
|
class ProjectLinksSpider(scrapy.Spider):
|
|
name = 'links'
|
|
|
|
def __init__(self, website_name=None, start_urls=None, config_path=None, allowed_domains=None):
|
|
super(ProjectLinksSpider, self).__init__()
|
|
self.config = ConfigParser()
|
|
self.config_path = config_path
|
|
self.website_name = website_name
|
|
self.allowed_domains = allowed_domains.split(',') if allowed_domains else []
|
|
self.start_urls = start_urls
|
|
if config_path:
|
|
with open(os.getcwd() + config_path, 'r') as f:
|
|
self.config.read_file(f)
|
|
self.project_links = []
|
|
|
|
def start_requests(self):
|
|
xpath = dict(self.config.items(self.website_name))
|
|
for url in self.start_urls:
|
|
yield scrapy.Request(url=url, callback=self.parse, meta={'xpath': xpath}, dont_filter=True)
|
|
|
|
|
|
def parse(self, response):
|
|
xpath = response.meta.get('xpath', {})
|
|
# Extract links
|
|
for project in response.xpath(xpath['project-list']):
|
|
link = response.urljoin(project.xpath(xpath['project-link']).get())
|
|
yield{
|
|
'link': link
|
|
}
|
|
self.project_links.append(link)
|
|
|
|
# Handle pagination
|
|
next_page = response.xpath(xpath['next-btn'])
|
|
if next_page is not None:
|
|
next_url = response.urljoin(next_page.get())
|
|
if next_url != response.url:
|
|
self.logger.info(f"Following next page: {next_url}")
|
|
yield scrapy.Request(url=next_url, callback=self.parse, dont_filter=True, meta={'xpath':xpath})
|
|
else:
|
|
self.save_links()
|
|
|
|
def save_links(self):
|
|
df = pd.DataFrame(self.project_links, columns=['project_link'])
|
|
df.to_json(f'project_links_{self.website_name}.json', orient='records')
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
'''
|
|
import scrapy
|
|
from configparser import ConfigParser
|
|
import os
|
|
import pandas as pd
|
|
import logging
|
|
|
|
|
|
|
|
class ProjectLinksSpider(scrapy.Spider):
|
|
name = 'links'
|
|
|
|
def __init__(self, website_name='DFG', start_urls='https://gepris.dfg.de/gepris/OCTOPUS?context=projekt&findButton=historyCall&hitsPerPage=125&index=0&keywords_criterion=Universit%C3%A4t+Duisburg-Essen&nurProjekteMitAB=false&orderBy=relevance&task=doSearchSimple', config_path='./config/links_config.ini', allowed_domains='gepris.dfg.de'):
|
|
super(ProjectLinksSpider, self).__init__()
|
|
self.config = ConfigParser()
|
|
self.config_path = config_path
|
|
self.website_name = website_name
|
|
self.allowed_domains = allowed_domains.split(',') if allowed_domains else []
|
|
self.start_urls = start_urls.split(',') if start_urls else []
|
|
if config_path:
|
|
with open(os.getcwd() + config_path, 'r') as f:
|
|
self.config.read_file(f)
|
|
self.project_links = []
|
|
|
|
def start_requests(self):
|
|
xpath = dict(self.config.items(self.website_name))
|
|
print(xpath)
|
|
for url in self.start_urls:
|
|
yield scrapy.Request(url=url, callback=self.parse, meta={'xpath': xpath}, dont_filter=True)
|
|
|
|
|
|
def parse(self, response):
|
|
xpath = response.meta.get('xpath', {})
|
|
# Extract links
|
|
for project in response.xpath(xpath['project-list']):
|
|
link = response.urljoin(project.xpath(xpath['project-link']).get())
|
|
yield{
|
|
'link': link
|
|
}
|
|
self.project_links.append(link)
|
|
|
|
# Handle pagination
|
|
next_page = response.xpath(xpath['next-btn'])
|
|
if next_page is not None:
|
|
next_url = response.urljoin(next_page.get())
|
|
if next_url != response.url:
|
|
self.logger.info(f"Following next page: {next_url}")
|
|
yield scrapy.Request(url=next_url, callback=self.parse, dont_filter=True, meta={'xpath':xpath})
|
|
else:
|
|
self.save_links()
|
|
|
|
def save_links(self):
|
|
df = pd.DataFrame(self.project_links, columns=['project_link'])
|
|
df.to_json(f'project_links_{self.website_name}.json', orient='records')
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
'''
|
|
|
|
import requests
|
|
from scrapy.crawler import CrawlerProcess
|
|
import argparse
|
|
import json
|
|
import logging
|
|
from requests.exceptions import MissingSchema
|
|
from scrapyscript.spiders.project_links import ProjectLinksSpider
|
|
from seleniumscript.project_links import ProjectLinksSelenium
|
|
from seleniumscript.project_data import ProjectDataSelenium
|
|
from scrapyscript.spiders.project_data import ProjectDataSpider
|
|
|
|
|
|
def main(start_urls):
|
|
|
|
def is_dynamic():
|
|
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:55.0) Gecko/20100101 Firefox/55.0'}
|
|
response = requests.get(url=start_urls, headers=headers)
|
|
|
|
if input('Do you have to fill out an HTML form to access the project links?(y/n): ').lower() == 'y' or input('Does the search criteria appear in the URL as a parameter?(y/n): ').lower() == 'n' :
|
|
print('Framework uses Selenium to scrape project calls')
|
|
return True
|
|
|
|
elif input('Does the website load the entire page at once without delay?(y/n): ').lower() == 'n':
|
|
if '<noscript' in response.text:
|
|
print('Framework uses Selenium to scrape project calls')
|
|
return True
|
|
else:
|
|
print('Framework uses Scrapy to scrape project calls')
|
|
return False
|
|
|
|
|
|
|
|
def scrape_data_dynamic(project_links, website_name):
|
|
logging.info('Scraping project data...')
|
|
body_wait_time = int(input("Enter the amount of time you want to wait for each page to load in seconds: "))
|
|
xpath_wait_time = int(input("Enter the amount of time you want to wait for each field to load in seconds: "))
|
|
config_xpath = input("Enter the path to your xpath configuration file: ")
|
|
ProjectDataSelenium(urls=project_links,
|
|
website_name=website_name,
|
|
body_wait_time=body_wait_time,
|
|
xpath_wait_time=xpath_wait_time,
|
|
config_xpath=config_xpath)
|
|
|
|
|
|
|
|
def scrape_links_dynamic(start_urls, website_name, config_path):
|
|
logging.info('Scraping project links...')
|
|
body_wait_time = int(input("Enter the amount of time you want to wait for each page to load in seconds: "))
|
|
xpath_wait_time = int(input("Enter the amount of time you want to wait for each field to load in seconds: "))
|
|
ProjectLinksSelenium(start_urls=start_urls,
|
|
website_name=website_name,
|
|
config_path=config_path,
|
|
body_wait_time=body_wait_time,
|
|
xpath_wait_time=xpath_wait_time)
|
|
links = access_stored_links(website_name)
|
|
start_urls = [link['project_link'] for link in links]
|
|
scrape_data_dynamic(start_urls,website_name)
|
|
|
|
def scrape_data_static(project_links, website_name, allowed_domains):
|
|
|
|
config_xpath = input("Enter the path to your xpath configuration file: ")
|
|
process = CrawlerProcess()
|
|
process.crawl(ProjectDataSpider,
|
|
start_urls=project_links,
|
|
config_xpath=config_xpath,
|
|
website_name=website_name,
|
|
allowed_domains=allowed_domains)
|
|
def scrape_links_static(start_urls,config_path, website_name, allowed_domains):
|
|
process = CrawlerProcess()
|
|
process.crawl(ProjectLinksSpider,
|
|
website_name=website_name,
|
|
start_urls=start_urls,
|
|
config_path=config_path,
|
|
allowed_domains=allowed_domains)
|
|
process.start()
|
|
links = access_stored_links(website_name)
|
|
start_urls = [link['project_link'] for link in links]
|
|
scrape_data_static(project_links=start_urls, website_name=website_name, allowed_domains=allowed_domains)
|
|
|
|
def access_stored_links(name):
|
|
try:
|
|
with open(f'./project_links_{name}.json', 'r', encoding='utf-8') as f:
|
|
jsonlinks = json.load(f)
|
|
return jsonlinks
|
|
except FileNotFoundError:
|
|
print('File not found')
|
|
|
|
|
|
if is_dynamic():
|
|
website_name = input("Enter website name: ")
|
|
config_path = input("Enter path to links_config.ini: ")
|
|
scrape_links_dynamic(start_urls, website_name, config_path)
|
|
else:
|
|
website_name = input("Enter website name: ")
|
|
config_path = input("Enter the path to links_config.ini: ")
|
|
allowed_domains = input("Enter allowed domains: ")
|
|
scrape_links_static(start_urls=start_urls, config_path=config_path, website_name=website_name, allowed_domains=allowed_domains)
|
|
|
|
|
|
if __name__ == '__main__':
|
|
parser = argparse.ArgumentParser()
|
|
parser.add_argument('--start-urls', type=str, help='The start URL of the website to scrape')
|
|
args = parser.parse_args()
|
|
try:
|
|
main(start_urls=args.start_urls)
|
|
except (MissingSchema):
|
|
logging.error('Please provide the start URL of the website to scrape as string. Example: python main.py --start-urls "https://www.example.com"')
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
# if input('Do you have to fill out an HTML form to access the project links?(y/n): ').lower() == 'y':
|
|
# print('The website is dynamic')
|
|
# return True
|
|
# # 2
|
|
# elif input('Does the search criteria appear in the URL as a parameter?(y/n): ').lower() == 'n':
|
|
# print('The website is dynamic')
|
|
# return True
|
|
# # 3
|
|
# elif input('Does the website load the entire page at once without delay?(y/n): ').lower() == 'n':
|
|
# print('The website is dynamic')
|
|
# return True
|
|
# else:
|
|
# print('The website is static')
|
|
# return False
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
'''import requests
|
|
from scrapy.crawler import CrawlerProcess
|
|
import argparse
|
|
from scrapy.spiders import CallbackSpider
|
|
import json
|
|
import logging
|
|
from requests.exceptions import MissingSchema
|
|
from scrapyscript.spiders.project_links import ProjectLinksSpider
|
|
from seleniumscript.project_links import ProjectLinksSelenium
|
|
from seleniumscript.project_data import ProjectDataSelenium
|
|
from scrapyscript.spiders.project_data import ProjectDataSpider
|
|
|
|
|
|
def main(start_urls):
|
|
|
|
def is_dynamic():
|
|
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:55.0) Gecko/20100101 Firefox/55.0'}
|
|
response = requests.get(url=start_urls, headers=headers)
|
|
|
|
if input('Do you have to fill out an HTML form to access the project links?(y/n): ').lower() == 'y' or input('Does the search criteria appear in the URL as a parameter?(y/n): ').lower() == 'n' :
|
|
print('Framework uses Selenium to scrape project calls')
|
|
return True
|
|
|
|
elif input('Does the website load the entire page at once without delay?(y/n): ').lower() == 'n':
|
|
if '<noscript' in response.text:
|
|
print('Framework uses Selenium to scrape project calls')
|
|
return True
|
|
else:
|
|
print('Framework uses Scrapy to scrape project calls')
|
|
return False
|
|
|
|
|
|
|
|
def scrape_data_dynamic(project_links, website_name):
|
|
logging.info('Scraping project data...')
|
|
body_wait_time = int(input("Enter the amount of time you want to wait for each page to load in seconds: "))
|
|
xpath_wait_time = int(input("Enter the amount of time you want to wait for each field to load in seconds: "))
|
|
config_xpath = input("Enter the path to your xpath configuration file: ")
|
|
ProjectDataSelenium(urls=project_links,
|
|
website_name=website_name,
|
|
body_wait_time=body_wait_time,
|
|
xpath_wait_time=xpath_wait_time,
|
|
config_xpath=config_xpath)
|
|
|
|
|
|
|
|
def scrape_links_dynamic(start_urls, website_name, config_path):
|
|
logging.info('Scraping project links...')
|
|
body_wait_time = int(input("Enter the amount of time you want to wait for each page to load in seconds: "))
|
|
xpath_wait_time = int(input("Enter the amount of time you want to wait for each field to load in seconds: "))
|
|
ProjectLinksSelenium(start_urls=start_urls,
|
|
website_name=website_name,
|
|
config_path=config_path,
|
|
body_wait_time=body_wait_time,
|
|
xpath_wait_time=xpath_wait_time)
|
|
links = access_stored_links(website_name)
|
|
start_urls = [link['project_link'] for link in links]
|
|
scrape_data_dynamic(start_urls,website_name)
|
|
|
|
def scrape_data_static(project_links, website_name, allowed_domains):
|
|
config_xpath = input("Enter the path to your xpath configuration file: ")
|
|
process = CrawlerProcess()
|
|
process.crawl(ProjectDataSpider,
|
|
start_urls=project_links,
|
|
config_xpath=config_xpath,
|
|
website_name=website_name,
|
|
allowed_domains=allowed_domains)
|
|
process.start()
|
|
def scrape_links_static(start_urls,config_path, website_name, allowed_domains):
|
|
process = CrawlerProcess()
|
|
process.crawl(ProjectLinksSpider,
|
|
website_name=website_name,
|
|
start_urls=start_urls,
|
|
config_path=config_path,
|
|
allowed_domains=allowed_domains)
|
|
def callback():
|
|
links = access_stored_links(website_name)
|
|
start_urls = [link['project_link'] for link in links]
|
|
scrape_data_static(project_links=start_urls, website_name=website_name, allowed_domains=allowed_domains)
|
|
process.crawl(CallbackSpider, callback=callback)
|
|
process.start()
|
|
links = access_stored_links(website_name)
|
|
start_urls = [link['project_link'] for link in links]
|
|
scrape_data_static(process=process, project_links=start_urls, website_name=website_name, allowed_domains=allowed_domains)
|
|
|
|
def access_stored_links(name):
|
|
try:
|
|
with open(f'./project_links_{name}.json', 'r', encoding='utf-8') as f:
|
|
jsonlinks = json.load(f)
|
|
return jsonlinks
|
|
except FileNotFoundError:
|
|
print('File not found')
|
|
|
|
|
|
if is_dynamic():
|
|
website_name = input("Enter website name: ")
|
|
config_path = input("Enter path to links_config.ini: ")
|
|
scrape_links_dynamic(start_urls, website_name, config_path)
|
|
else:
|
|
website_name = input("Enter website name: ")
|
|
config_path = input("Enter the path to links_config.ini: ")
|
|
allowed_domains = input("Enter allowed domains: ")
|
|
scrape_links_static(start_urls=start_urls, config_path=config_path, website_name=website_name, allowed_domains=allowed_domains)
|
|
|
|
|
|
if __name__ == '__main__':
|
|
parser = argparse.ArgumentParser()
|
|
parser.add_argument('--start-urls', type=str, help='The start URL of the website to scrape')
|
|
args = parser.parse_args()
|
|
try:
|
|
main(start_urls=args.start_urls)
|
|
except (MissingSchema):
|
|
logging.error('Please provide the start URL of the website to scrape as string. Example: python main.py --start-urls "https://www.example.com"')
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
# if input('Do you have to fill out an HTML form to access the project links?(y/n): ').lower() == 'y':
|
|
# print('The website is dynamic')
|
|
# return True
|
|
# # 2
|
|
# elif input('Does the search criteria appear in the URL as a parameter?(y/n): ').lower() == 'n':
|
|
# print('The website is dynamic')
|
|
# return True
|
|
# # 3
|
|
# elif input('Does the website load the entire page at once without delay?(y/n): ').lower() == 'n':
|
|
# print('The website is dynamic')
|
|
# return True
|
|
# else:
|
|
# print('The website is static')
|
|
# return False
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
'''
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|