模拟登录流程:

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. sed命令详解--转

    1.简介 sed是非交互式的编辑器.它不会修改文件,除非使用shell重定向来保存结果.默认情况下,所有的输出行都被打印到屏幕上. sed编辑器逐行处理文件(或输入),并将结果发送到屏幕.具体过程如下 ...

  2. Android开发之Bitmap二次采样

    Bitmap二次采样,听着好像是一个高大上的事,其实也就那么回事,今天我们就来看看Bitmap的二次采样问题. 1.为什么要二次采样 OK,那么首先我要 解决的一个问题就是为什么我们要二次采样? 不知 ...

  3. css :after和:before

    :before是css中的一种伪元素,可用于在某个元素之前插入某些内容.:after是css中的一种伪元素,可用于在某个元素之后插入某些内容. 举例: 1.结合border写个对话框的样式. < ...

  4. 监控Linux内存使用情况

    cat mem.sh#!/bin/bashIP=`ifconfig | grep 'inet ' | grep -v '127.0.0.1' | awk -F ' ' '{print $2}'| aw ...

  5. Hadoop的伪分布式搭建

    我们在搭建伪分布式Hadoop环境,需要将一系列的配置文件配置好. 一.配置文件 1. 配置文件hadoop-env.sh export JAVA_HOME=/opt/modules/jdk1.7.0 ...

  6. HTML文本格式化

    文本格式化标签: 标签 描述 <b> 定义粗体文本. <big> 定义大号字. <em> 定义着重文字. <i> 定义斜体字. <small> ...

  7. spring中@param和mybatis中@param使用区别

    spring中@param /** * 查询指定用户和企业关联有没有配置角色 * @param businessId memberId * @return */ int selectRoleCount ...

  8. Java_Web学习笔记_过滤器应用案例(解决全站字符乱码)

    解决全站字符乱码(POST和GET中文编码问题) servlet: l  POST:request.setCharacterEncoding(“utf-8”); l  GET: String user ...

  9. 用正则表达式解析XML

    import java.util.regex.*; import java.util.*; /** * * <p>Title: Document</p> * * <p&g ...

  10. 不一样的编码风格--Lambda表达式

    Lambda表达式也是C#3.0中最重要的特性之一. 1.Lambda表达式的简介 Lambda表达式可以理解为一个匿名方法,它可以包含表达式和语句,并且用于创建委托或转换为表达式树.在使用Lambd ...