简体   繁体   English

全球名称 <function> 未定义的错误Python

[英]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 在spider(1)的第27行,spider details(href)的第22行中NameError:未定义全局名称'details'

I already tried the self.details(href) method, but there was an additional error saying it could not resolve "self". 我已经尝试过self.details(href)方法,但是还有另一个错误,说它无法解析“ 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. 由于您在文件的def details() spider(1)之前调用了spider(1) ,因此该函数details()尚不为人所知。

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. 您至少应将调用spider(1)移动到以def details()开头的函数定义之后,您可以将def spider():def details()之前的行保留下来,只要在需要执行所有操作时调用spider()即可spider()是“已知的”,即在到目前为止已处理的文件中进行解析。

If you define detail function like this: 如果您像这样定义明细函数:

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

Then, you could call self.details. 然后,您可以调用self.details。 Although I don't quite get your error... 虽然我不太明白您的错误...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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