As part of my quest to learn Python, I'm writing a wrapper over the MediaWiki API to return article texts.
Here's the function to search for an article:
def article_search(self, search_terms):
url = self.article_url % (self.language, search_terms)
response = requests.get(url)
tree = html.fromstring(response.text)
results = tree.xpath('//rev[@contentmodel='wikitext']/text()')
test_redirect = re.search('\#REDIRECT', str(results))
if test_redirect:
redirect = re.search(r'\[\[([A-Za-z0-9_]+)\]\]', str(results))
go_to = redirect.group(1)
article_search(go_to)
else:
return results
The goal of the if-else block is to check to see if the search result actually is trying to redirect us to another page (if test_redirect
) and then search for the page that we're being redirected to with article_search(go_to)
. When I run the code on a page that I know doesn't redirect, it works fine. However, when I run it over a page that does have a redirect, I get NameError: global name 'article_search' is not defined
. I get the feeling this is probably a newbie question, but I'm not really sure what I'm doing wrong. Any help?
I assume that article_search
is part of a class (since you use self
). In that case you should call it like that:
self.article_search(go_to)
(assuming it is not a weird staticmethod but a method of an instance)