views:

267

answers:

3

Hello. 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?
+2  A: 

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
Nick Craig-Wood
maybe, but I was looking for a more efficient solution
roddik
+2  A: 

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.
Lennart Regebro
The first one isn't possible, unfortunately, gonna try the second one
roddik
No way, open resets everything :(
roddik
+1  A: 

And the correct answer:

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