title: How to use mechanize package inside a function to log into website?
body: <p>I am using mechanize to log into a website and scrape it with beautifulsoap. While I got it working without using functions, I don't know how to put the login-functionality into a function and then later use it in the main program. Here's my not working code so far:</p>
  <pre><code>#!/usr/bin/env python
  
  import http.cookiejar as cookielib
  import mechanize
  from bs4 import BeautifulSoup
  
  def set_browser():
      br = mechanize.Browser()
      cookiejar = cookielib.LWPCookieJar()
      br.set_cookiejar(cookiejar)
      br.set_handle_equiv(True)
      br.set_handle_gzip(True)
      br.set_handle_redirect(True)
      br.set_handle_referer(True)
      br.set_handle_robots(False)
      br.set_handle_refresh(mechanize._http.HTTPRefreshProcessor(), max_time = 1)
      br.addheaders = [( 'User-agent', 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.1) Gecko/2008071615 Fedora/3.0.1-1.fc9 Firefox/3.0.1' )]
      return br
  
  def login(br):
      br.open(&quot;https://example.com/login/index.php&quot;)
      br.select_form(nr=0)
      br.form['username'] = &quot;admin&quot;
      br.form['password'] = &quot;mypassword&quot;
      br.submit()
  
  def scrape():
      url = &quot;https://example.com/content&quot;
      data = br.open(url).get_data()
      soup = BeautifulSoup(data, 'html.parser')
      with open(&quot;source.html&quot;, &quot;w&quot;) as text_file:
          print(soup.prettify(), file=text_file)
  
  if __name__ == &quot;__main__&quot;:
      set_browser()
      login(br)
      scrape()
  </code></pre>
  <p>I hope someone can help me how to write proper functions. In my above code, I wrote two functions set_browser() and login() but it isn't important to have two functions; if both are combined into one, it will be okay, I just split it into two to really learn using functions.</p>