我正在尝试编写一个函数来发布表单数据并将返回的cookie信息保存在文件中,以便下次访问页面时,cookie信息将被发送到服务器(即正常的浏览器行为).
我使用curlib在C++中相对容易地编写了这个,但是花了将近一整天的时间尝试使用urllib2在Python中编写它 - 但仍然没有成功.
这是我到目前为止:
import urllib, urllib2
import logging
# the path and filename to save your cookies in
COOKIEFILE = 'cookies.lwp'
cj = None
ClientCookie = None
cookielib = None
logger = logging.getLogger(__name__)
# Let's see if cookielib is available
try:
import cookielib
except ImportError:
logger.debug('importing cookielib failed. Trying ClientCookie')
try:
import ClientCookie
except ImportError:
logger.debug('ClientCookie isn\'t available either')
urlopen = urllib2.urlopen
Request = urllib2.Request
else:
logger.debug('imported ClientCookie succesfully')
urlopen = ClientCookie.urlopen
Request = ClientCookie.Request
cj = ClientCookie.LWPCookieJar() …Run Code Online (Sandbox Code Playgroud)