python 处理cookie简单很多啊 httpclient版本是4.3.3
模拟登录流程: 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的更多相关文章
- Python - Django - Cookie 简单用法
home.html: <!DOCTYPE html> <html lang="en"> <head> <meta charset=&quo ...
- python之cookie, cookiejar 模拟登录绕过验证
0.思路 如果懒得模拟登录,或者模拟登录过于复杂(多步交互或复杂验证码)则人工登录后手动复制cookie(或者代码读取浏览器cookie),缺点是容易过期. 如果登录是简单的提交表单,代码第一步模拟登 ...
- 用Python写一个简单的Web框架
一.概述 二.从demo_app开始 三.WSGI中的application 四.区分URL 五.重构 1.正则匹配URL 2.DRY 3.抽象出框架 六.参考 一.概述 在Python中,WSGI( ...
- Python 2.7.x 和 3.x 版本的重要区别
许多Python初学者都会问:我应该学习哪个版本的Python.对于这个问题,我的回答通常是“先选择一个最适合你的Python教程,教程中使用哪个版本的Python,你就用那个版本.等学得差不多了,再 ...
- python之simplejson,Python版的简单、 快速、 可扩展 JSON 编码器/解码器
python之simplejson,Python版的简单. 快速. 可扩展 JSON 编码器/解码器 simplejson Python版的简单. 快速. 可扩展 JSON 编码器/解码器 编码基本的 ...
- Python 2.7.x 和 3.x 版本的重要区别小结
许多Python初学者都会问:我应该学习哪个版本的Python.对于这个问题,我的回答通常是"先选择一个最适合你的Python教程,教程中使用哪个版本的Python,你就用那个版本.等学得差 ...
- Python django实现简单的邮件系统发送邮件功能
Python django实现简单的邮件系统发送邮件功能 本文实例讲述了Python django实现简单的邮件系统发送邮件功能. django邮件系统 Django发送邮件官方中文文档 总结如下: ...
- Session会话与Cookie简单说明
会话(Session)跟踪是Web程序中常用的技术,用来跟踪用户的整个会话.常用的会话跟踪技术是Cookie与Session.Cookie通过在客户端记录信息确定用户身份,Session通过在服务器端 ...
- python之pandas简单介绍及使用(一)
python之pandas简单介绍及使用(一) 一. Pandas简介1.Python Data Analysis Library 或 pandas 是基于NumPy 的一种工具,该工具是为了解决数据 ...
随机推荐
- android夸项目调用
将工程A做成android library project. 设置工程A,右键->Properties->Android,将Is library项选中,然后Apply.设置工程B,右键-& ...
- Java代码安全测试解决方案
Java代码安全测试解决方案: http://gdtesting.com/product.php?id=106
- Find Security Bugs研究,邀请志同道合者一起参与
Find Security Bugs研究,邀请志同道合者一起参与http://automationqa.com/forum.php?mod=viewthread&tid=2803&fr ...
- 一个不错的flash 模板
听到好听的背景音乐,而且效果也挺不错的,忽然感觉flash好强大呀 1.模板浏览地址:http://www.cssmoban.com/cssthemes/5229.shtml 2.模板演示地址:htt ...
- Log4Net详细配置
关于Log4Net配置主要分几步 第一步:下载log4net.dll(log4net官网:http://logging.apache.org/log4net/download_log4net.cgi) ...
- 那天有个小孩跟我说LINQ(五)转载
2 LINQ TO SQL(代码下载) 我们以一个简单的销售的业务数据库为例子 表结构很简单:Users(购买者(用户)表),Products(产品信息表),Sales(销 ...
- Web开发必备资源汇总[转]
导读:原文来自< Best “must know” open sources to build the new Web>,译文由酷壳网陈皓整理编译< 开源中最好的Web开发的资源 & ...
- 数组做为参数传入Oracle存储过程操作数据库
p { margin-bottom: 0.25cm; direction: ltr; color: rgb(0, 0, 0); line-height: 120%; text-align: justi ...
- xcode编译运行报错纪录(持续更新)
---恢复内容开始--- 1. Undefined symbols for architecture i386: "_deflate", referenced from: -[NS ...
- 浅谈break 、continue、return,goto四种语句的区别。
浅谈break .continue.return三种语句的区别: break,continue,return这三个具有跳转功能的语句在c语言中经常被用到,近期身边有些小伙伴总是把它们的用法搞乱,在这里 ...