模拟登录流程:

1 请求host_url

2 从host_url中解析出 隐藏表单 的值 添加到POST_DATA中

3 添加账户,密码到POST_DATA中

4 编码后,发送POST请求
    要点1:java下,HttpClient必须是单例模式
    要点2:post的url可能跟登录界面的url不同。post_url可以从host_url的返回结果中得到(具体情况自行分析)
    
5 通过firefox,chrome等相关插件验证登录完成 6 测试需要登录的采集任务 # --*-- coding:utf-8 --*--
import re
import cookielib
import urllib2
import urllib username = 'your account'
pwd = 'your pwd' hosturl = 'https://passport.csdn.net/account/login'
posturl = 'https://passport.csdn.net/account/login' cj = cookielib.LWPCookieJar()
cookie_support = urllib2.HTTPCookieProcessor(cj)
opener = urllib2.build_opener(cookie_support, urllib2.HTTPHandler)
urllib2.install_opener(opener) host_page = urllib2.urlopen(hosturl)
html = host_page.read() def getgroup_1(res, input):
pat = re.compile(res)
m = pat.search(input)
if m:
return m.group(1)
else:
return None res_lt = 'name="lt" value="(.*?)"'
lt = getgroup_1(res_lt, html) res_exe = 'name="execution" value="(.*?)"'
exe = getgroup_1(res_exe, html) print 'hidden post data', lt, exe headers = {'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:16.0) Gecko/20100101 Firefox/16.0'} post_data = {'_eventId': 'submit', 'execution': exe, 'lt': lt, 'username': username, 'password': pwd}
post_data = urllib.urlencode(post_data) request = urllib2.Request(posturl, post_data, headers)
print request
response = urllib2.urlopen(request)
txt = response.read()
print txt
附带:java代码。。。。。。。。要点是httpclient必须是同一个实例
public class LoginTest { private static String getGroup_1(String res, String input){
Pattern p = Pattern.compile(res);
Matcher m = p.matcher(input);
while(m.find()){
return m.group(1);
}
return null;
} public static void main(String[] args) {//登录csdn
String uri = "https://passport.csdn.net/account/login";
String html = HttpUtil.DownHtml(uri); // <input type="hidden" name="lt" value="LT-207426-moK0sGnfCa9aqijJKeLYhFDYiEe2id" />
// <input type="hidden" name="execution" value="e1s1" />
// <input type="hidden" name="_eventId" value="submit" /> String lt = getGroup_1("name=\"lt\" value=\"(.*?)\"", html);
String execution = getGroup_1("name=\"execution\" value=\"(.*?)\"", html);
System.out.println(lt + "\t" + execution); //构建cookie
Map<String, String> params = new HashMap<String,String>();
params.put("_eventId", "submit");
params.put("execution", execution);
params.put("lt", lt);
params.put("password", "******");
params.put("username", "******"); HttpUtil.Post(uri, params); System.out.println(System.currentTimeMillis()); }
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern; import org.apache.http.Header;
import org.apache.http.HeaderIterator;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils; public class HttpUtil { private static CloseableHttpClient httpclient = null;
  //要点:单例模式
static {
if (httpclient == null) {
httpclient = HttpClients.createDefault();
}
} public static void Post(String uri, Map<String, String> params) { HttpPost httpost = new HttpPost(uri);
List<NameValuePair> post_data = new ArrayList<NameValuePair>(); Set<String> keySet = params.keySet();
for (String key : keySet) {
post_data.add(new BasicNameValuePair(key, params.get(key)));
} CloseableHttpResponse response = null; try {
httpost.setHeader("User-Agent",
"Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:16.0) Gecko/20100101 Firefox/16.0"); httpost.setEntity(new UrlEncodedFormEntity(post_data, "UTF-8"));
response = httpclient.execute(httpost); HeaderIterator it = response.headerIterator();
while (it.hasNext()) {
System.out.println(it.next());
}
System.out.println("---------------html---------------"); HttpEntity entity = response.getEntity();
String body = EntityUtils.toString(entity);
System.out.println(body); } catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static String DownHtml(String uri) { HttpGet httpget = new HttpGet(uri);
CloseableHttpResponse response = null; System.out.println(httpget.getURI());
System.out.println("Executing request " + httpget.getRequestLine()); try {
response = httpclient.execute(httpget); System.out.println(response.getStatusLine().toString());
System.out.println("------------------------------"); // 头信息
HeaderIterator it = response.headerIterator();
StringBuffer buff = new StringBuffer();
while (it.hasNext()) {
buff.append(it.next());
// System.out.println(it.next());
}
System.out.println("------------------------------"); // 判断访问的状态码
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
System.err
.println("Method failed: " + response.getStatusLine());
} HttpEntity entity = response.getEntity();
// String charset = EntityUtils.getContentCharSet(entity);
StringBuilder pageBuffer = new StringBuilder();
if (entity != null) {
InputStream in = entity.getContent();
BufferedReader br = new BufferedReader(new InputStreamReader(
in, "UTF-8"));
String line;
while ((line = br.readLine()) != null) {
pageBuffer.append(line);
pageBuffer.append("\n");
}
in.close();
br.close();
}
return pageBuffer.toString(); } catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}

python 处理cookie简单很多啊 httpclient版本是4.3.3的更多相关文章

  1. Python - Django - Cookie 简单用法

    home.html: <!DOCTYPE html> <html lang="en"> <head> <meta charset=&quo ...

  2. python之cookie, cookiejar 模拟登录绕过验证

    0.思路 如果懒得模拟登录,或者模拟登录过于复杂(多步交互或复杂验证码)则人工登录后手动复制cookie(或者代码读取浏览器cookie),缺点是容易过期. 如果登录是简单的提交表单,代码第一步模拟登 ...

  3. 用Python写一个简单的Web框架

    一.概述 二.从demo_app开始 三.WSGI中的application 四.区分URL 五.重构 1.正则匹配URL 2.DRY 3.抽象出框架 六.参考 一.概述 在Python中,WSGI( ...

  4. Python 2.7.x 和 3.x 版本的重要区别

    许多Python初学者都会问:我应该学习哪个版本的Python.对于这个问题,我的回答通常是“先选择一个最适合你的Python教程,教程中使用哪个版本的Python,你就用那个版本.等学得差不多了,再 ...

  5. python之simplejson,Python版的简单、 快速、 可扩展 JSON 编码器/解码器

    python之simplejson,Python版的简单. 快速. 可扩展 JSON 编码器/解码器 simplejson Python版的简单. 快速. 可扩展 JSON 编码器/解码器 编码基本的 ...

  6. Python 2.7.x 和 3.x 版本的重要区别小结

    许多Python初学者都会问:我应该学习哪个版本的Python.对于这个问题,我的回答通常是"先选择一个最适合你的Python教程,教程中使用哪个版本的Python,你就用那个版本.等学得差 ...

  7. Python django实现简单的邮件系统发送邮件功能

    Python django实现简单的邮件系统发送邮件功能 本文实例讲述了Python django实现简单的邮件系统发送邮件功能. django邮件系统 Django发送邮件官方中文文档 总结如下: ...

  8. Session会话与Cookie简单说明

    会话(Session)跟踪是Web程序中常用的技术,用来跟踪用户的整个会话.常用的会话跟踪技术是Cookie与Session.Cookie通过在客户端记录信息确定用户身份,Session通过在服务器端 ...

  9. python之pandas简单介绍及使用(一)

    python之pandas简单介绍及使用(一) 一. Pandas简介1.Python Data Analysis Library 或 pandas 是基于NumPy 的一种工具,该工具是为了解决数据 ...

随机推荐

  1. HD1285(拓扑排序)

    package cn.hncu.dataStruct.search.topSort; import java.util.Scanner; public class Hdu1285 { static S ...

  2. 第一章建立asp.net MVC

    第一步 第二步 创建controller 创建View view和controller之间的关系

  3. iOS tableview 静态表布局纪录

    今天使用了tableview静态表布局,纪录如下 1:使用tableview 静态表,必须是UITableViewController 2:Content 中选择 Static Cells 如下图 3 ...

  4. java.util.Stack类简介

    Stack是一个后进先出(last in first out,LIFO)的堆栈,在Vector类的基础上扩展5个方法而来 Deque(双端队列)比起Stack具有更好的完整性和一致性,应该被优先使用 ...

  5. 关于Modelsim仿真速度的优化

    如果在不需要波形,只需要快速知道结果的情况下,可以用优化选项.这适用于做大量case的仿真阶段.因为这一阶段多数case都是通过的,只需要快速确认即可,然后把没通过的case拿出来做全波形的仿真调试. ...

  6. MySQL(5.6) 函数

    字符串函数 ASCII(str) 说明:返回字符串 str 最左边字符的 ASCII 值 mysql'); mysql); mysql> SELECT ASCII('a'); mysql> ...

  7. Velocity 入门(一)

    Velocity是一种Java模版引擎技术,该项目由Apache提出.因为非常好用,和工作中有啥用,所以我在在理简单的入门一下. 网上找了很多教程,写的不是很明白,要么就是全部拷贝下来时候运行不起来. ...

  8. Base64 encode/decode large file

    转载:http://www.cnblogs.com/jzywh/archive/2008/04/20/base64_encode_large_file.html The class System.Co ...

  9. ACM——圆柱体的表面积

    lems 1092 圆柱体的表面积 时间限制(普通/Java):1000MS/3000MS          运行内存限制:65536KByte总提交:2697            测试通过:414 ...

  10. PHPSession-完全PHP5之session篇

    http://blog.csdn.net/masterft/article/details/1640122 1.什么是session?       Session的中文译名叫做“会话”,其本来的含义是 ...