Commit 09208038 by 周峻哲

chair网站爬虫

parent 79e48998
# Define here the models for your scraped items
#
# See documentation in:
# https://docs.scrapy.org/en/latest/topics/items.html
import scrapy
class ClaieCrawlerItem(scrapy.Item):
# define the fields for your item here like:
# name = scrapy.Field()
pass
# 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 ClaieCrawlerSpiderMiddleware:
# 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 ClaieCrawlerDownloaderMiddleware:
# 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)
# 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 ClaieCrawlerPipeline:
def process_item(self, item, spider):
return item
# Scrapy settings for claie_crawler 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 = "claie_crawler"
SPIDER_MODULES = ["claie_crawler.spiders"]
NEWSPIDER_MODULE = "claie_crawler.spiders"
# Crawl responsibly by identifying yourself (and your website) on the user-agent
#USER_AGENT = "claie_crawler (+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 = 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 = {
# "claie_crawler.middlewares.ClaieCrawlerSpiderMiddleware": 543,
#}
# Enable or disable downloader middlewares
# See https://docs.scrapy.org/en/latest/topics/downloader-middleware.html
#DOWNLOADER_MIDDLEWARES = {
# "claie_crawler.middlewares.ClaieCrawlerDownloaderMiddleware": 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 = {
# "claie_crawler.pipelines.ClaieCrawlerPipeline": 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"
# 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.
import scrapy
from urllib.parse import urljoin
import os
import pdfkit
class ClaieSpider(scrapy.Spider):
name = 'claie'
allowed_domains = ['claie.org']
start_urls = ['https://www.claie.org/']
#path_wkhtmltopdf = '/usr/local/bin/wkhtmltopdf' # 对于 MacOS/Linux
path_wkhtmltopdf = r'C:\Program Files\wkhtmltopdf\bin\wkhtmltopdf.exe' # 对于 Windows
config = pdfkit.configuration(wkhtmltopdf=path_wkhtmltopdf)
def parse(self, response):
# 提取页面内容,但过滤掉特定段落
unwanted_texts = [
'关于我们', '法律声明', '下载中心', '联系我们',
'支持:北京大学', '中国人民大学', '中国通用航空发展协会', '中国直升机产业发展协会', '欧美同学会企业家联谊会',
'协办:领导干部国学大讲堂 曲阜儒商会馆管理有限公司',
'版权所有:中国低空产业经济研究院 国城弦歌(北京)文化传播中心',
'http://claie.org', 'E-mail:907421288@qq.com',
'首页', '政策法规', '产业动态', '产业经济', '航校培训', '生产基地',
'维护租赁', '销售物流', '产业咨询', '产业案例', '园区规划', '应急救援',
'医疗救援', '消防救援', '农药喷洒', '海上救援', '地震救援', '俱乐部'
]
page_title = response.css('title::text').get()
all_texts = response.css('body *::text').getall()
# 过滤掉包含不需要内容的文本
page_content = ' '.join([
text.strip() for text in all_texts
if not any(unwanted in text for unwanted in unwanted_texts)
])
# 保存页面内容为PDF
self.save_page_as_pdf(response.url, page_title, page_content)
# 提取所有链接并递归爬取
for href in response.css('a::attr(href)').extract():
url = urljoin(response.url, href)
if self.allowed_domains[0] in url:
yield scrapy.Request(url, callback=self.parse)
def save_page_as_pdf(self, url, title, content):
# 创建一个文件夹来保存爬取的内容
directory = 'downloaded_pages_pdf'
if not os.path.exists(directory):
os.makedirs(directory)
# 创建临时HTML文件
html_content = f"""
<html>
<head>
<meta charset="utf-8">
<title>{title}</title>
</head>
<body>
<h1>{title}</h1>
<p><a href="{url}">{url}</a></p>
<p>{content}</p>
</body>
</html>
"""
# 创建文件名
filename = os.path.join(directory, f"{title[:50].strip().replace(' ', '_').replace('/', '_')}.pdf")
path_wkhtmltopdf = r'C:\Program Files\wkhtmltopdf\bin\wkhtmltopdf.exe' # 对于 Windows
config = pdfkit.configuration(wkhtmltopdf=path_wkhtmltopdf)
# 使用pdfkit保存为PDF文件
pdfkit.from_string(html_content, filename)
self.log(f'Saved page as PDF {filename}')
import datetime
from apscheduler.schedulers.background import BackgroundScheduler
import os
import pdfkit
import scrapy
from scrapy.crawler import CrawlerProcess
from scrapy.utils.project import get_project_settings
from urllib.parse import urljoin
class ClaieSpider(scrapy.Spider):
name = 'claie'
allowed_domains = ['claie.org']
start_urls = ['https://www.claie.org/']
path_wkhtmltopdf = r'C:\Program Files\wkhtmltopdf\bin\wkhtmltopdf.exe' # 对于 Windows
config = pdfkit.configuration(wkhtmltopdf=path_wkhtmltopdf)
# path_wkhtmltopdf = '/usr/local/bin/wkhtmltopdf' # 对于 Linux
# config = pdfkit.configuration(wkhtmltopdf=path_wkhtmltopdf)
def parse(self, response):
unwanted_texts = [
'关于我们', '法律声明', '下载中心', '联系我们',
'支持:北京大学', '中国人民大学', '中国通用航空发展协会', '中国直升机产业发展协会', '欧美同学会企业家联谊会',
'协办:领导干部国学大讲堂 曲阜儒商会馆管理有限公司',
'版权所有:中国低空产业经济研究院 国城弦歌(北京)文化传播中心',
'http://claie.org', 'E-mail:907421288@qq.com',
'首页', '政策法规', '产业动态', '产业经济', '航校培训', '生产基地',
'维护租赁', '销售物流', '产业咨询', '产业案例', '园区规划', '应急救援',
'医疗救援', '消防救援', '农药喷洒', '海上救援', '地震救援', '俱乐部'
]
page_title = response.css('title::text').get()
all_texts = response.css('body *::text').getall()
page_content = ' '.join([
text.strip() for text in all_texts
if not any(unwanted in text for unwanted in unwanted_texts)
])
self.save_page_as_pdf(response.url, page_title, page_content)
for href in response.css('a::attr(href)').extract():
url = urljoin(response.url, href)
if self.allowed_domains[0] in url:
yield scrapy.Request(url, callback=self.parse)
def save_page_as_pdf(self, url, title, content):
directory = 'downloaded_pages_pdf'
if not os.path.exists(directory):
os.makedirs(directory)
html_content = f"""
<html>
<head>
<meta charset="utf-8">
<title>{title}</title>
</head>
<body>
<h1>{title}</h1>
<p><a href="{url}">{url}</a></p>
<p>{content}</p>
</body>
</html>
"""
filename = os.path.join(directory, f"{title[:50].strip().replace(' ', '_').replace('/', '_')}.pdf")
config = pdfkit.configuration(wkhtmltopdf=self.path_wkhtmltopdf)
pdfkit.from_string(html_content, filename, configuration=config)
self.log(f'Saved page as PDF {filename}')
class TaskScheduler:
def __init__(self):
self.scheduler = BackgroundScheduler()
def add_task(self, timedTask):
# 使用 cron 触发器每天凌晨2点执行任务
self.scheduler.add_job(timedTask, 'cron', hour=9, minute=46)
def start_scheduler(self):
self.scheduler.start()
def stop_scheduler(self):
self.scheduler.shutdown()
def run_spider():
process = CrawlerProcess(get_project_settings())
process.crawl(ClaieSpider)
process.start()
if __name__ == "__main__":
scheduler = TaskScheduler()
scheduler.add_task(run_spider) # 每天早晨10点执行一次爬虫
scheduler.start_scheduler()
try:
while True:
pass
except KeyboardInterrupt:
scheduler.stop_scheduler()
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment