需要用python模拟登录后,模拟发表文章。但没学过phthon所以一直在百度。
self.ckjar = cookielib.MozillaCookieJar("cookies.txt")
ckproc = urllib2.HTTPCookieProcessor(self.ckjar)
self.opener = urllib2.build_opener(ckproc)
urllib2.install_opener(self.opener)
post_data = urllib.urlencode({
'username' : username,
'password' : password,
})
#发送登录POST
post_url = 'http://www.test.com/login'
req = urllib2.Request(url = post_url, data = post_data)
resp = urllib2.urlopen(req)
tem = resp.read()
resp.close()
self.ckjar.save(ignore_discard=True, ignore_expires=True)
这段代码是为urllib2操作统一添加cookies,可以正常登录并发表文章。又需要上传图片,网上找到代码如下
datagen, headers = multipart_encode({"file": open("test.jpeg", "rb")})
post_url = 'http://www.test.com/webuploader.php'
request = urllib2.Request(post_url, datagen, headers)
resp = urllib2.urlopen(request)
图片可以正常发送,但是没有带cookies登录信息,不明白,找到下面的代码解决了
from poster.encode import multipart_encode
from poster.streaminghttp import register_openers
opener = register_openers()
opener.add_handler(urllib2.HTTPCookieProcessor(self.ckjar))
resp = urllib2.urlopen(request)
content = resp.read()
虽然还是有些不明所以,但也没有太多精力去研究,就这样吧。