重拾Scrapy框架

基于Scrapy框架實現 舔狗語錄+百度翻譯 輸出結果到txt文檔
爬蟲腳本

from typing import Iterable, Any, AsyncIteratorimport scrapy
import json
from post.items import PostItemclass 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 piexcept Exception as e:continuedef 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.htmlimport scrapyclass 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 datetimeclass 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 itemdef 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.htmlBOT_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.pswp.cn/diannao/85546.shtml
繁體地址,請注明出處:http://hk.pswp.cn/diannao/85546.shtml
英文地址,請注明出處:http://en.pswp.cn/diannao/85546.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

【實例】事業單位學習平臺自動化操作

目錄 一、創作背景: 二、實現邏輯: 三、代碼分析【Deepseek分析】: 1) 主要功能 2)核心組件 2.1 GUI界面 (AutomationApp類) 2.2 瀏覽器自動化 2.3 平臺特定處理 3) 關鍵技術 4)代碼亮點 5)總結 四、運行截圖: 五、程序代碼: 特別聲明:***本代碼僅限編程學…

CSS篇-1

1. CSS 有哪些基本選擇器?它們的權重是如何表示的? 這是一個關于 CSS 基礎且極其重要的問題,因為它直接關系到我們如何精準地控制頁面元素的樣式,以及在樣式沖突時瀏覽器如何決定哪個樣式生效。理解 CSS 選擇器及其權重(或稱為“優先級”或“特殊性”),是編寫高效、可維…

封裝一個Qt調用動態庫的類

封裝一個Qt調用動態庫的類 由于我的操作系統Ubuntu系統,我就以Linux下的動態庫.so為例了,其實windows上的dll庫調用方式是一樣的,如果你的Qt項目是windows的,這篇文章代碼可以直接使用。 一般情況下我們對外輸出都是以動態庫的形式封裝的,這樣我們更新版本的時候就很方便…

陰盤奇門 api數據接口

陰盤奇門,又稱"道家陰盤遁甲"或"法術奇門",與陽盤奇門(奇門排盤)并稱"奇門雙雄"。由王鳳麟教授整合道家三式(奇門、六壬、太乙)精髓創立,獨創行為風水與立體全息預測技術,廣…

【計算機網絡】第3章:傳輸層—可靠數據傳輸的原理

目錄 一、PPT 二、總結 (一)可靠數據傳輸原理 關鍵機制 1. 序號機制 (Sequence Numbers) 2. 確認機制 (Acknowledgements - ACKs) 3. 重傳機制 (Retransmission) 4. 校驗和 (Checksum) 5. 流量控制 (Flow Control) 協議實現的核心:滑…

C#實現圖片縮略圖生成:多種模式詳解與實踐

C#實現圖片縮略圖生成:多種模式詳解與實踐 在圖像處理的場景中,生成圖片縮略圖是一項常見且實用的功能。無論是搭建圖片展示網站,還是開發本地圖片管理工具,按需生成合適尺寸的縮略圖,能夠有效減少圖片傳輸和顯示所需…

2025年- H57-Lc165--994.腐爛的橘子(圖論,廣搜)--Java版

1.題目描述 2.思路 3.代碼實現 import java.util.LinkedList; import java.util.Queue;public class H994 {public int orangesRotting(int[][] grid) {//1.獲取行數int rowsgrid.length;int colsgrid[0].length;//2.創建隊列用于bfsQueue<int[]> quenew LinkedList<…

005 flutter基礎,初始文件講解(4)

書接上回&#xff0c;今天繼續完成最后的講解&#xff1a; class _MyHomePageState extends State<MyHomePage> {int _counter 0;void _incrementCounter() {setState(() {_counter;});}可以看到&#xff0c;這里的_MyHomePageState是一個類&#xff0c;繼承于 State&l…

DeepSeek R1開源模型的技術突破與AI產業格局的重構

引言? 2025年&#xff0c;中國AI企業深度求索&#xff08;DeepSeek&#xff09;推出的開源模型DeepSeek-R1&#xff0c;以低成本、高性能和開放生態為核心特征&#xff0c;成為全球人工智能領域的技術焦點。這一模型不僅通過算法創新顯著降低算力依賴&#xff0c;更通過開源策…

輕量級swiper插件推薦

推薦插件列表&#xff08;按體積從小到大排序&#xff09; 1. Embla Carousel 體積&#xff1a;約 5KB (gzipped) 官網&#xff1a;A lightweight carousel library with fluid motion and great swipe precision | Embla Carousel 特點&#xff1a; 極小體積&#xff0c;高…

設計模式——訪問者設計模式(行為型)

摘要 訪問者設計模式是一種行為型設計模式&#xff0c;它將數據結構與作用于結構上的操作解耦&#xff0c;允許在不修改數據結構的前提下增加新的操作行為。該模式包含關鍵角色如元素接口、具體元素類、訪問者接口和具體訪問者類。通過訪問者模式&#xff0c;可以在不改變對象…

Vue基礎(12)_Vue.js循環語句用法:列表渲染

js補充 術語解釋 循環(loop)&#xff1a;最基礎的概念, 所有重復的行為。 遞歸(recursion)&#xff1a; 在函數內調用自身, 將復雜情況逐步轉化成基本情況。 (數學)迭代(iterate) &#xff1a;在多次循環中逐步接近結果。 (編程)迭代(iterate) &#xff1a;按順序訪問線性結構中…

Linux入門(十三)動態監控系統監控網絡狀態

top與ps 命令很相似&#xff0c;它們都是用來顯示正在執行的進程&#xff0c;top與ps大的區別是top在執行一段時間可以更新正在運行的進程。 #-d 更新秒數 如果不寫-d 那默認是3秒更新 # -i 隱藏不活躍進程 top -d 5交互操作 P 按cpu使用大小排序&#xff0c;默認此項 M 按內存…

Java 中 MySQL 索引深度解析:面試核心知識點與實戰

&#x1f91f;致敬讀者 &#x1f7e9;感謝閱讀&#x1f7e6;笑口常開&#x1f7ea;生日快樂?早點睡覺 &#x1f4d8;博主相關 &#x1f7e7;博主信息&#x1f7e8;博客首頁&#x1f7eb;專欄推薦&#x1f7e5;活動信息 文章目錄 Java 中 MySQL 索引深度解析&#xff1a;面試…

Kafka集成Flume/Spark/Flink(大數據)/SpringBoot

Kafka集成Flume Flume生產者 ③、安裝Flume&#xff0c;上傳apache-flume的壓縮包.tar.gz到Linux系統的software&#xff0c;并解壓到/opt/module目錄下&#xff0c;并修改其名稱為flume Flume消費者 Kafka集成Spark 生產者 object SparkKafkaProducer{def main(args:Array[S…

debian12.9或ubuntu,vagrant離線安裝插件vagrant-libvirt,20250601

系統盤: https://mirror.lzu.edu.cn/debian-cd/12.9.0/amd64/iso-dvd/debian-12.9.0-amd64-DVD-1.iso 需要的依賴包,無需安裝ruby( sudo apt install -y ruby-full ruby-dev rubygems,后來發現不安裝會有編譯警告,還是安裝吧 ) ,無需安裝 zlib1g-dev liblzma-dev libxml2-de…

2025年軟件測試面試八股文(含答案+文檔)

&#x1f345; 點擊文末小卡片&#xff0c;免費獲取軟件測試全套資料&#xff0c;資料在手&#xff0c;漲薪更快 Part1 1、你的測試職業發展是什么&#xff1f; 測試經驗越多&#xff0c;測試能力越高。所以我的職業發展是需要時間積累的&#xff0c;一步步向著高級測試工程師…

[CSS3]響應式布局

導讀 響應式就是一套代碼, 兼容大中小不同的屏幕, 即網頁內容不變, 網頁布局隨屏幕切換而改變 媒體查詢 響應式布局的核心技術是媒體查詢 媒體查詢可以檢測屏幕尺寸, 設置差異化的css 開發中的常用寫法 使用范圍屬性, 劃定屏幕范圍 max-width 最大寬度min-width 最小寬度 …

在 Windows安裝 make 的幾種方式

在 Windows 上使用 make&#xff08;通常用于自動化構建 C/C 項目等&#xff09;有幾種方法。以下是最常見的幾種安裝和使用方法&#xff1a; 文章目錄 ? 方法一&#xff1a;使用 Chocolatey 安裝 GNU Make&#xff08;推薦&#xff09;? 方法二&#xff1a;使用 WSL&#xf…

深度學習筆記25-RNN心臟病預測(Pytorch)

&#x1f368; 本文為&#x1f517;365天深度學習訓練營中的學習記錄博客&#x1f356; 原作者&#xff1a;K同學啊 一、前期準備 1.數據處理 import torch.nn.functional as F import numpy as np import pandas as pd import torch from torch import nn dfpd.read_csv(r&…