重拾Scrapy框架

news2025/12/14 18:51:31

基于Scrapy框架实现 舔狗语录+百度翻译 输出结果到txt文档
爬虫脚本

from typing import Iterable, Any, AsyncIterator

import scrapy
import json
from post.items import PostItem


class BaidufanyiSpider(scrapy.Spider):
    name = "baidufanyi"
    allowed_domains = ["fanyi.baidu.com", "api.oick.cn"]
    start_urls = ["https://api.oick.cn/api/dog"]
    headers = {
        "Content-Type": "application/json",
    }

    def __init__(self):
        super().__init__()

    def parse_post(self, response):
        word = response.meta["word"]
        for line in response.body.decode("utf-8").split("\n"):
            try:
                new_data = json.loads(line.lstrip("data: "))
                event = new_data["data"]["event"]
                if event == "Translating":
                    pi = PostItem()
                    pi["org"] = new_data["data"]["list"][0]["src"]
                    pi["res"] = new_data["data"]["list"][0]["dst"]
                    if word == new_data["data"]["list"][0]["src"]:
                        yield pi

            except Exception as e:
                continue

    def parse(self, response):
        yield scrapy.Request(url=self.start_urls[0], callback=self.parse_detail)

    def parse_detail(self, response):
        word = response.text.strip('"')
        url = "https://fanyi.baidu.com/ait/text/translate"
        data = {
            "query": f"{word}",
            "from": "zh",
            "to": "en",
            "needPhonetic": True,
        }
        yield scrapy.FormRequest(url=url, method="POST", headers=self.headers, body=json.dumps(data),
                                 callback=self.parse_post, meta={"word": word})

        yield scrapy.Request(url=self.start_urls[0], callback=self.parse_detail,dont_filter=True)

items.py

# Define here the models for your scraped items
#
# See documentation in:
# https://docs.scrapy.org/en/latest/topics/items.html

import scrapy


class PostItem(scrapy.Item):
    # define the fields for yo在这里插入代码片ur item here like:
    # name = scrapy.Field()
    org = scrapy.Field()
    res = scrapy.Field()

piplines.py

# 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
from datetime import datetime



class PostPipeline:

    def open_spider(self, spider):
        self.f = open('result.txt', 'a', encoding='utf-8')

    def process_item(self, item, spider):
        new_item = f'{item["org"]}\t{item["res"]}\t{datetime.now().strftime("%Y-%m-%d %H:%M:%S")}\n'
        self.f.write(new_item)
        self.f.flush()
        return item

    def close_spider(self, spider):
        self.f.close()

settings.py

# Scrapy settings for post 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 = "post"

SPIDER_MODULES = ["post.spiders"]
NEWSPIDER_MODULE = "post.spiders"

ADDONS = {}

# Crawl responsibly by identifying yourself (and your website) on the user-agent
# USER_AGENT = "post (+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 = 60 / 120
RANDOMIZE_DOWNLOAD_DELAY = True
# 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 = {
#    "post.middlewares.PostSpiderMiddleware": 543,
# }

# Enable or disable downloader middlewares
# See https://docs.scrapy.org/en/latest/topics/downloader-middleware.html
# DOWNLOADER_MIDDLEWARES = {
#    "post.middlewares.PostDownloaderMiddleware": 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 = {
    "post.pipelines.PostPipeline": 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
FEED_EXPORT_ENCODING = "utf-8"

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2393279.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

XPlifeapp:高效打印,便捷生活

在数字化时代,虽然电子设备的使用越来越普遍,但打印的需求依然存在。无论是学生需要打印课表、资料,还是职场人士需要打印名片、报告,一个高效便捷的打印软件都能大大提高工作效率。XPlifeapp就是这样一款超级好用的手机打印软件&…

等保测评-Mysql数据库测评篇

Mysql数据库测评 0x01 前言 "没有网络安全、就没有国家安全" 等保测评是什么? 等保测评(网络安全等级保护测评)是根据中国《网络安全法》及相关标准,对信息系统安全防护能力进行检测评估的法定流程。其核心依据《信…

02.K8S核心概念

服务的分类 有状态服务:会对本地环境产生依赖,例如需要把数据存储到本地磁盘,如mysql、redis; 无状态服务:不会对本地环境产生任何依赖,例如不会存储数据到本地磁盘,如nginx、apache&#xff…

一篇文章玩转CAP原理

CAP 原理是分布式系统设计的核心理论之一,揭示了系统设计中的 根本性权衡。 一、CAP 的定义 CAP 由三个核心属性组成,任何分布式系统最多只能同时满足其中两个: 一致性(Consistency) 所有节点在同一时刻看到的数据完全…

Vue-收集表单信息

收集表单信息 Input label for 和 input id 关联, 点击账号标签 也能聚焦 input 代码 <!DOCTYPE html> <html lang"en"><head><meta charset"UTF-8" /><title>表单数据</title><!-- 引入Vue --><scrip…

vscode开发stm32,main.c文件中出现很多报错影响开发解决日志

本质上为 .vscode/c_cpp_properties.json文件和Makefile文件中冲突&#xff0c;两者没有同步。 将makefile文件中的内容同步过来即可&#xff0c;下面给出一个json文件的模板&#xff0c;每个人的情况不同&#xff0c;针对性修改即可 {"configurations": [{"na…

嵌入式鸿蒙系统中水平和垂直以及图片调用方法

利用openharmony操作的具体现象: 第一:Column 作用:沿垂直方向布局的容器。 第二:常用接口 Column(value?: {space?: string | number}) 参数: 参数名参数类型必填参数描述spacestring | number否纵向布局元素垂直方向间距。 从API version 9开始,space为负数或者ju…

【海康USB相机被HALCON助手连接过后,MVS显示无法连接故障。】

在Halcon里使用助手调用海康USB相机时&#xff0c;如果这个界面点击了【是】 那么恭喜你&#xff0c;相机只能被HALCON调用使用&#xff0c;使用MVS或者海康开发库&#xff0c;将查找不到相机 解决方式&#xff1a; 右键桌面【此电脑】图标 ->选择【管理】 ->选择【设备…

2025年电气工程与轨道交通国际会议:绿色能源与智能交通的创新之路

2025年电气工程与轨道交通国际会议&#xff08;ICEERT 2025&#xff09;是一场电气工程与轨道交通领域的国际盛会&#xff0c;将于2025年在武汉隆重召开。此次会议汇聚了全球顶尖的专家学者和行业精英&#xff0c;共同探讨电气工程与轨道交通的最新研究成果和技术趋势。会议将围…

WPF log4net用法

WPF log4net用法 一、在工程中管理NuGet程序包&#xff0c;找到log4net&#xff0c;点击安装&#xff0c;如下图已成功安装&#xff1b; 二、在工程中右键添加新建项&#xff0c;选择应用程序配置文件&#xff08;后缀为.config&#xff09;,然后设置名称&#xff0c;这里设置…

数字孪生数据监控如何提升汽车零部件工厂产品质量

一、汽车零部件工厂的质量挑战 汽车零部件作为汽车制造的基础&#xff0c;其质量直接关系到整车的性能、可靠性和安全性。在传统的汽车零部件生产过程中&#xff0c;质量问题往往难以在早期阶段被发现和解决&#xff0c;导致生产效率低下、生产成本上升&#xff0c;甚至影响到…

贪心算法实战3

文章目录 前言区间问题跳跃游戏跳跃游戏II用最少数量的箭引爆气球无重叠区间划分字母区间合并区间 最大子序和加油站监控二叉树 前言 今天继续带大家进行贪心算法的实战篇3&#xff0c;本章注意来解答一些运用贪心算法的比较难的问题&#xff0c;大家好好体会&#xff0c;怎么…

实测,大模型谁更懂数据可视化?

大家好&#xff0c;我是 Ai 学习的老章 看论文时&#xff0c;经常看到漂亮的图表&#xff0c;很多不知道是用什么工具绘制的&#xff0c;或者很想复刻类似图表。 实测&#xff0c;大模型 LaTeX 公式识别&#xff0c;出乎预料 前文&#xff0c;我用 Kimi、Qwen-3-235B-A22B、…

Linux入门(十一)进程管理

Linux 中每个执行的程序都称为一个进程&#xff0c;每个进程都分配一个ID号&#xff08;PID&#xff09; 每个进程都可能以两种方式存在&#xff0c;前台&#xff08;屏幕上可以操作的&#xff09;和后台&#xff08;屏幕上无法看到的&#xff09;&#xff0c;一般系统的服务都…

【技能篇】RabbitMQ消息中间件面试专题

1. RabbitMQ 中的 broker 是指什么&#xff1f;cluster 又是指什么&#xff1f; 2. 什么是元数据&#xff1f;元数据分为哪些类型&#xff1f;包括哪些内容&#xff1f;与 cluster 相关的元数据有哪些&#xff1f;元数据是如何保存的&#xff1f;元数据在 cluster 中是如何分布…

Linux研学-环境搭建

一 概述 1 Linux 概述 Linux系统由内核、Shell、文件系统、应用程序及系统库等关键部分组成。内核作为核心&#xff0c;管理硬件资源与系统服务&#xff1b;Shell提供用户与系统交互的命令行界面&#xff0c;让用户能便捷执行操作&#xff1b;文件系统负责数据的存储、组织与管…

Ubuntu系统下可执行文件在桌面单击运行教程

目录 ​编辑 操作环境&#xff1a;这个可执行文件在原目录下还有它的依赖文件 1&#xff0c;方法1&#xff1a;创建启动脚本 操作步骤​&#xff1a; &#xff08;1&#xff09;​​在桌面创建脚本文件​​&#xff08;如 run_main_improve.sh&#xff09;&#xff1a; ​…

Linux之文件进程间通信信号

Linux之文件&进程间通信&信号 文件文件描述符文件操作重定向缓冲区一切皆文件的理解文件系统磁盘物理结构&块文件系统结构 软硬链接 进程间通信匿名管道命名管道system V共享内存 信号 文件 首先&#xff0c;Linux下一切皆文件。对于大量的文件&#xff0c;自然要…

代码随想录算法训练营 Day61 图论ⅩⅠ Floyd A※ 最短路径算法

图论 题目 97. 小明逛公园 本题是经典的多源最短路问题。 在这之前我们讲解过&#xff0c;dijkstra朴素版、dijkstra堆优化、Bellman算法、Bellman队列优化&#xff08;SPFA&#xff09; 都是单源最短路&#xff0c;即只能有一个起点。 而本题是多源最短路&#xff0c;即求多…

改写自己的浏览器插件工具 myChromeTools

1. 起因&#xff0c; 目的: 前面我写过&#xff0c; 自己的一个浏览器插件小工具 最近又增加一个小功能&#xff0c;可以自动滚动页面&#xff0c;尤其是对于那些瀑布流加载的网页。最新的代码都在这里 2. 先看效果 3. 过程: 代码 1, 模拟鼠标自然滚动 // 处理滚动控制逻辑…