amccormack.net

Things I've learned and suspect I'll forget.

BrowserStateError in mechanize

I've been working through Violent Python this weekend and ran into a problem with mechanize. The book lists the following code:

import mechanize
def viewPage(url):
    browser = mechanize.Browser()
    page = browser.open(url)
    source_code = page.read()
    print source_code
viewPage('http://www.syngress.com')

I, however, used the following sample code:

>>> import mechanize
>>> def viewPage(url):
    browser = mechanize.Browser()
    page = browser.open(url)
    source_code = page.read()
    print source_code

>>> viewPage('www.google.com')

Traceback (most recent call last):
  File "<pyshell#8>", line 1, in <module>
    viewPage('www.google.com')
  File "<pyshell#7>", line 3, in viewPage
    page = browser.open(url)
  File "build\bdist.win32\egg\mechanize\_mechanize.py", line 203, in open
    return self._mech_open(url, data, timeout=timeout)
  File "build\bdist.win32\egg\mechanize\_mechanize.py", line 216, in _mech_open
    "can't fetch relative reference: "
BrowserStateError: can't fetch relative reference: not viewing any document

The difference, of course is that I didn't put the 'http' in front of the url. Thus, if you happen to get the error "BrowserStateError: can't fetch relative reference: not viewing any document", be sure that the protocol is included in the url.

published on 2013-01-27 21:28:11 by alex