2

I practice Scrapy and want to ask a question:

I know how to use def printTW when it out of the class
How can I calling it when I write it inside class ?
My code is here: Please teach me

from scrapy.spider import Spider
from scrapy.selector import Selector
from yahoo.items import YahooItem

def printTW(original_line):
    for words in original_line:
        print words.encode('utf-8')     

class MySpider(Spider):   
    name = "yahoogo"
    start_urls = ["https://tw.movies.yahoo.com/chart.html"]  

    #Don't know how to calling this
    #def printTW(original_line):
    #    for words in original_line:
    #        print words.encode('utf-8')     

    def parse(self, response):
        for sel in response.xpath("//tr"):
            movie_description = sel.xpath("td[@class='c3']/a/text()").extract()
            printTW(movie_description) 
falsetru
  • 357,413
  • 63
  • 732
  • 636
user2492364
  • 6,543
  • 22
  • 77
  • 147

2 Answers2

2

To call instance method, you need to qualify the method with self.

self.printTW(movie_description) 

And the method should have a self as the first parameter:

def printTW(self, original_line):
    for words in original_line:
        print words.encode('utf-8')     

Because the printTW does not use any instance attribute, you can define the method as static method (or you can define it as function, not a method).

@staticmethod
def printTW(original_line):
    for words in original_line:
        print words.encode('utf-8')     
falsetru
  • 357,413
  • 63
  • 732
  • 636
0

Declare the function as global within the method you wish to call it, like so:

def parse(self, response):
    global printTW
    for sel in response.xpath("//tr"):
        movie_description = sel.xpath("td[@class='c3']/a/text()").extract()
        printTW(movie_description) 
jmduke
  • 1,657
  • 1
  • 13
  • 11