claie.py 3.04 KB
Newer Older
周峻哲 committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75
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}')