Question

There is a Python mechanize object with a form with almost all values set, but not yet submitted. Now I want to fetch another page using cookies from mechanize instance, but without resetting the page, forms and so on, e.g. so that the values remain set (I just need to get body string of another page, nothing else). So is there a way to:

  1. Tell mechanize not to reset the page (perhaps, through UserAgentBase)?
  2. Make urllib2 use mechanize's cookie jar? NB: urllib2.HTTPCookieProcessor(self.br._ua_handlers["_cookies"].cookiejar) doesn't work
  3. Any other way to pass cookie to urllib?
Was it helpful?

Solution

And the correct answer:

opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(self.br._ua_handlers["_cookies"].cookiejar))
opener.open(imgurl)

OTHER TIPS

No idea whether this will work, but why don't you try deepcopying the mechanize instance, eg

from copy import deepcopy
br = Browser()
br.open("http://www.example.com/")
# Make a copy for doing other stuff with
br2 = deepcopy(br)
# Do stuff with br2
# Now do stuff with br

Some wild ideas:

  • Fetch the second page before filling in the form?
  • Or fetch the new page and then goBack()? Although maybe that will reset the values.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top