【发布时间】:2021-11-23 11:31:07
【问题描述】:
我有这个简单的代码:
import scrapy
import re
import json
# from scrapy.http import FormRequest
from scrapy.spiders import CrawlSpider, Rule
from scrapy.linkextractors import LinkExtractor
class SpiderRecipe(CrawlSpider):
name = "recipe"
start_urls = [
# 'https://www.giallozafferano.it/',
'https://ricetta.it/dolci?page=1',
# 'https://www.buonissimo.it/',
# 'https://migusto.migros.ch/it.html'
]
def parse(self,response):
URL = response.request.url()
if URL.split('/')[2] == "www.ricetta.it":
recipes = response.xpath('//div[contains(@class,"row")]/div[contains(@class,"post-img-left")]').extract()
# iterate through each recipe in a page
for x in recipes.extract():
title = response.xpath(recipes + '/a[contains(@class, "post-title")]/text()').extract()[x]
image = response.xpath(recipes + '/div[contains(@class,"videoContainer")]/img/@src').extract()[x]
description = response.xpath(recipes + '/p[contains(@class,"post-excerpt")]/text()').extract()[x]
yield {
'Title': title,
'Image': image,
'Description': description,
}
page = int(URL.split('=')[1]) + 1;
if (page <= 148):
# iterate through each page of recipes
yield scrapy.Request(URL.split('=')[0] + str(page), callback=self.parse, dont_filter=True)
终端使用scrapy runspider recipe.py -o output.json调用。
codw 的第一部分有效,因为它可以采用起始 URL,但我不明白为什么不调用 parse 函数,如果代码不正确,我尝试在开头打印函数一个字符串,但它没有工作。我试图检查解决方案,但我的函数在类中,并且我已经正确插入了我们必须开始的 url(链接是正确的)。也许这很容易,但我找不到。我还读到必须调用该函数,但在示例中没有人这样做,此外我在代码末尾不断调用它。
【问题讨论】:
-
你在哪里打电话
parse()? -
在上面的代码中,
SpiderRecipe类被声明了,但在任何时候都没有实例化;你也可以发布你实例化它的部分代码吗? -
@Haroldo_OK 我使用scrapy runspider recipe.py -o output.json 调用终端中的代码,如果这就是你的意思。第一部分有效,我可以打印 url_starts,但从不调用该方法
-
@Patrick 正如我所说,我认为我不必调用 parse() 因为它应该是通过在终端中调用蜘蛛来自动实现的
-
@Patrick 这意味着我必须添加例如一个方法 start 来发出调用方法解析的请求?像此链接第二个示例中的方法 def start_requests(self) 一样吗? docs.scrapy.org/en/latest/intro/tutorial.html
标签: python scrapy web-crawler