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 的一种工具,该工具是为了解决数据 ...
随机推荐
- Xcode 4-PBXcp error修复-No such file or directory
Xcode 4-PBXcp error修复-No such file or directory (2013-05-02 15:20:50) 转载▼ 标签: apple iphone ios 移动开发 ...
- 对于POI的XSSFCell 类型问题
1.XSSFCell.CELL_TYPE_BLANK 2.XSSFCell.CELL_TYPE_BOOLEAN 取值方式:cell.getBooleanCellValue() 3.XSSFCell.C ...
- hdu 1587 Flowers
Flowers Time Limit: 1000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others) Total Su ...
- .Net程序员快速学习安卓开发-布局和点击事件的写法
关注今日头条-做全栈攻城狮,学代码也要读书,爱全栈,更爱生活.提供程序员技术及生活指导干货. 本系列课程 致力于老手程序员可以快速入门学习安卓开发.系统全面的从一个.Net程序员的角度一步步学习总结安 ...
- java 用eclipse j2ee写的servlet 程序,WEB-INF下的配置文件web.xml在哪啊?谢谢!
我用的版本是tomcat7.0,在webcontent\web-inf里只有一个空文件夹lib,写完servlet 类程序,就可以运行了,我想知道自动生成的配置文件在哪里?或者说从哪里能够看出来配置内 ...
- MVC知识总结(前序)
距离2015年的来临还有1天的时间,是时候总结一下今年的经过脑子的知识了,由于今年里工作中接触MVC的时间特别多,所以打算针对MVC这个东西的知识进行一个总结,好歹对得起在几个项目中用了MVC来进行开 ...
- 20151225jquery学习笔记---选项卡UI
圣诞节快乐,哈哈哈....选项卡(tab),是一种能提供给用户在同一个页面切换不同内容的 UI. 尤其是在页面布局紧凑的页面上,提供了非常好的用户体验.一. 使用 tabs使用 tabs 比较简单,但 ...
- SQL Server 脚本语句
一.语法结构 select select_list [ into new_table ] from table_source [ where search_condition ] [ group by ...
- 学习笔记6_Java_day11_JSP_基础和入门(1、2)
主要内容:1. JSP基础2. Cookie3. HttpSession ================================ JSP基础 1. jsp的作用: * Servlet: &g ...
- asp.net WebService异步
1 #region 异步测试 2 //委托 3 public delegate void PrintDelegate(string s); 4 [WebMethod] 5 public string ...