简体   繁体   中英

Global Name <function> not defined error Python

I have a function

def details(href):
    response = requests.get(href)
    soup = BeautifulSoup(response.content)
    genre =  soup.find(text="Genre: ").next_sibling.text
    print genre

that I am trying to call inside another function

def spider(max_pages):
    page = 1
    while page <= max_pages:
        url = 'http://www.boxofficemojo.com/yearly/chart/?page=' + str(page) + '&view=releasedate&view2=domestic&yr=2013&p=.htm'
        source_code = requests.get(url)
        plain_text = source_code.text
        soup = BeautifulSoup(plain_text)
        for link in soup.select('td > b > font > a[href^=/movies/?]'):
            href = 'http://www.boxofficemojo.com' + link.get('href')
            details(href)
            title = link.string
            listOfTitles.append(title)
        page += 1
spider(1)

I am getting an error

line 27, in spider(1) line 22, in spider details(href) NameError: global name 'details' is not defined

I already tried the self.details(href) method, but there was an additional error saying it could not resolve "self". How can I fix this?

Since you call spider(1) before the def details() in the file, that function details() is not known yet.

You should at least move the call spider(1) behind the function definition starting with def details() , you can leave the def spider(): lines before the def details() as long as calling spider() happens when everything needed by spider() is "known", ie parsed in the file processed so far.

If you define detail function like this:

  def details(self, href):
      ......

Then, you could call self.details. Although I don't quite get your error...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM