【问题标题】:Using scrapy with Cherrypy?将scrapy与Cherrypy一起使用?
【发布时间】:2020-05-13 05:36:18
【问题描述】:

我有两个类 CountrySpider 类和 Country 类。我想从国家类中的 CountrySpider 调用 parse() 函数,但出现此错误

TypeError: parse() missing 1 required positional argument: 'response'

请注意:def parse(self, response)是scrapy.Spider类的一个内置函数,它接受reponse参数。

如何从国家类中调用这个函数 self.countriesSpider.parse() ?

import scrapy
import cherrypy

class CountriesSpider(scrapy.Spider):
    name = 'countries'
    allowed_domains = ['www.worldometers.info/']
    start_urls = ['https://www.worldometers.info/world-population/population-by-country/']

    def parse(self, response):        
        title = response.xpath("//h1/text()").get()        
        countries = response.xpath("//td/a/text()").getall()

        yield {
            'title': title,
            'countries': countries
        }

        return countries


class Countries(object):

    def __init__(self):
        # Create an instance of Snacks class
        self.countriesSpider = CountriesSpider()

    @cherrypy.expose    
    def index(self):
        return self.countriesSpider.parse()

if __name__ == '__main__':
    cherrypy.quickstart(Countries())

【问题讨论】:

  • 它应该解析什么?
  • 您定义的parse 函数采用response 参数。你需要给它那个参数,或者你需要重写函数以不需要它。它不会凭空出现。
  • 它返回一个像这样的列表 {'title': 'Countries in the world by population (2020)', 'countries': ['China', 'India', 'United States', '印度尼西亚”、“巴基斯坦”、“巴西”、“尼日利亚”、“孟加拉国”、“俄罗斯”]}
  • 如果你想从另一个脚本启动你的蜘蛛,你需要使用from scrapy.crawler import CrawlerProcess

标签: python python-3.x oop scrapy


【解决方案1】:

您的函数需要一个名为 response 的参数。你没有输入参数。

【讨论】:

    猜你喜欢
    • 2012-05-26
    • 1970-01-01
    • 2014-02-10
    • 2015-06-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多