在Python scrapy项目中传递全局变量的问题

时间:2015-03-29 20:01:09

标签: python scrapy

在我正在做的Scrapy项目中,我很难将包含列表的变量从一个函数发送到另一个函数。我需要这样做,因为我需要在脚本结尾处将一个页面的值与另一个页面的值组合在一起。代码如下:

from scrapy.spider import Spider
from scrapy.selector import Selector
from scrapy.http import Request
from scrapy.http.request import Request
from dirbot.items import Website
from scrapy.contrib.spiders import CrawlSpider,Rule
from six import string_types
from datetime import datetime
from decimal import Decimal
import itertools
import numpy
import urlparse
import scrapy


class DmozSpider(Spider):
    name = "dnot"
    allowed_domains = ["ca.finance.yahoo.com", "http://eoddata.com/"]
    start_urls = [
        "http://eoddata.com/stocklist/TSX.htm"
    ]

    def parse(self,response):

        companyList = response.xpath('//tr[@class="ro"]/td/a/text()').extract()
        for company in companyList:
            go = 'https://ca.finance.yahoo.com/q/hp?s={0}.TO&a=02&b=2&c=2005&d=02&e=2&f=2015&g=m'.format(company)
            for link in go:
                yield Request(go, self.stocks1)

    def stocks1(self, response):

        # global returns_page1

        # EAFP = Easier to ask for forgiveness then permission
        # Gathers ONLY adjusted closing stock price 
        global returns_page1
        returns_page1 = []
        rows = response.xpath('//table[@class="yfnc_datamodoutline1"]//table/tr')[1:]
        for row in rows:
            cells = row.xpath('.//td/text()').extract()
            try:
                datetime.strptime(cells[0], "%b %d, %Y")
                values = cells[-1]
                returns_page1.append(values)
            except ValueError:
                continue  

        current_page = response.url
        next_page = current_page + "&z=66&y=66"
        yield Request(next_page, self.stocks2) 

    def stocks2(self, response):

        item = Website()
        global returns_page1
        returns_page2 = []

        rows = response.xpath('//table[@class="yfnc_datamodoutline1"]//table/tr')[1:]
        for row in rows:
            cells = row.xpath('.//td/text()').extract()
            try:
                datetime.strptime(cells[0], "%b %d, %Y")
                values = cells[-1]
                returns_page2.append(values)
            except ValueError:
                continue  

        returns_tot = returns_page1 + returns_page2
        returns_dec = [Decimal(float(i)) for i in returns_tot]
        returns = [float(n) for n in returns_dec]

        items = []
        item = Website()
        item['url'] = response.url
        item['name'] = response.xpath('//div[@class="title"]/h2/text()').extract()
        item['avgreturns'] = numpy.mean(returns)
        item['varreturns'] = numpy.var(returns)
        item['sdreturns'] = numpy.std(returns)
        item['returns'] = returns
        items.append(item)
        yield item

我正在尝试将returns_page1函数中的def stocks1returns_page2函数中收集的def stocks2结合起来。但是我的输出只给出了returns_page2变量的值。

我知道我不能在def stocks1函数中返回,因为我在那里有一个收益。这就是我尝试使用全局变量的原因。

我在这里做错了什么?

1 个答案:

答案 0 :(得分:3)

将值从一个函数传递到另一个函数的最佳方法是在请求中使用meta,

在第一个函数中

    yield Request(next_page, self.stocks2, meta={'returns_page1': returns_page1}) 

在第二个函数中

    returns_page1 = response.meta.get('returns_page1')