56 lines
2.0 KiB
Python
56 lines
2.0 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.split(',') if start_urls else []
|
|
logging.error(self.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))
|
|
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, meta={'xpath':xpath}, dont_filter=True)
|
|
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')
|
|
|