gpt4 book ai didi

python - 将 Scrapy 指向本地缓存而不是执行正常的爬取过程

转载 作者:行者123 更新时间:2023-11-28 18:36:05 25 4
gpt4 key购买 nike

我正在使用管道将 Scrapy 爬取的文档缓存到数据库中,这样如果我更改项目解析逻辑就可以重新解析它们而无需再次访问服务器。

从缓存中获取 Scrapy 进程而不是尝试执行正常抓取的最佳方法是什么?

我喜欢 scrapy 对 CSS 和 XPath 选择器的支持,否则我会使用 lxml 解析器单独访问数据库。

有一段时间,我根本没有缓存文档并以正常方式使用 Scrapy - 即时解析项目 - 但我发现更改项目逻辑需要时间和资源密集型重新抓取。相反,我现在将文档正文与项目解析一起缓存,并且我希望可以选择让 Scrapy 从数据库中遍历这些文档,而不是抓取目标 URL。

我如何着手修改 Scrapy,让我可以选择将一组文档传递给它,然后单独解析它们,就像它刚刚从网络上拉下来一样?

最佳答案

我认为 custom Downloader Middleware是个好方法。这个想法是让这个中间件直接从数据库返回源代码,不要让 Scrapy 发出任何 HTTP 请求。

示例实现(未经测试,绝对需要错误处理):

import re

import MySQLdb
from scrapy.http import Response
from scrapy.exceptions import IgnoreRequest
from scrapy import log
from scrapy.conf import settings


class CustomDownloaderMiddleware(object):
def __init__(self, *args, **kwargs):
super(CustomDownloaderMiddleware, self).__init__(*args, **kwargs)

self.connection = MySQLdb.connect(**settings.DATABASE)
self.cursor = self.connection.cursor()

def process_request(self, request, spider):
# extracting product id from a url
product_id = re.search(request.url, r"(\d+)$").group(1)

# getting cached source code from the database by product id
self.cursor.execute("""
SELECT
source_code
FROM
products
WHERE
product_id = %s
""", product_id)

source_code = self.cursor.fetchone()[0]

# making HTTP response instance without actually hitting the web-site
return Response(url=request.url, body=source_code)

别忘了 activate the middleware .

关于python - 将 Scrapy 指向本地缓存而不是执行正常的爬取过程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32407877/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com