53 lines
1.9 KiB
Python
53 lines
1.9 KiB
Python
import scrapy
|
|
from configparser import ConfigParser
|
|
import os
|
|
import codecs
|
|
import pandas as pd
|
|
import logging
|
|
|
|
|
|
class ProjectDataSpider(scrapy.Spider):
|
|
name = 'project-data'
|
|
def __init__(self,config_xpath=None, website_name=None, allowed_domains=None, start_urls=None):
|
|
super(ProjectDataSpider, self).__init__()
|
|
self.allowed_domains = allowed_domains.split(',') if allowed_domains else []
|
|
self.start_urls = start_urls
|
|
self.website_name = website_name
|
|
self.config_xpath = config_xpath
|
|
self.config = ConfigParser()
|
|
if config_xpath:
|
|
with codecs.open(os.getcwd() + config_xpath, 'r', encoding='utf-8') as f :
|
|
self.config.read_file(f)
|
|
self.items = []
|
|
|
|
|
|
def start_requests(self):
|
|
fields = self.config.items('fields')
|
|
for url in self.start_urls:
|
|
yield scrapy.Request(url, callback=self.parse, meta={'fields' : fields})
|
|
|
|
def parse(self, response):
|
|
fields = response.meta['fields']
|
|
item= {}
|
|
for field_name, xpath in fields:
|
|
output_list = response.xpath(xpath).extract()
|
|
try:
|
|
if len(output_list) == 1 :
|
|
item[field_name] = output_list[0].strip()
|
|
else:
|
|
item[field_name] = [output.strip() for output in output_list]
|
|
except Exception as e:
|
|
logging.error(f'An error occurred while parsing {field_name} :{e}')
|
|
item[field_name]=''
|
|
|
|
self.items.append(item)
|
|
|
|
def closed(self, reason):
|
|
""" This method is called when the spider is finished scraping.
|
|
It takes a reason parameter, which indicates why the spider is closing (e.g. 'finished' or 'shutdown'). """
|
|
df = pd.DataFrame(self.items)
|
|
df.to_json(f"scraped_data_{self.website_name}.json", orient='records', force_ascii=False)
|
|
|
|
|
|
|