python模拟登陆网页主要使用到urllib、urllib2、cookielib及BeautifulSoup等基本模块,当然进阶阶段我们还可以使用像requests等更高级一点的模块。其中BeautifulSoup模块在匹配html方面,可以很好的代替re,使用起来更方便,对于不会使用正则的人来说是福音。
本文使用python2.7
原理
模拟登陆前,我们需要先知道csdn是如何登陆的。我们通过google chrome浏览器先来分析下:
1.chrome浏览器用F12或ctrl+shift+I启动开发者工具,并访问csdn登陆页面,在开发者工具中对”Preserver log”选项打勾,表示跳转时不清楚之前的访问记录。
2.输入用户名密码后,网页进行跳转,此时我们查看访问记录中Method为POST的链接的headers,可以看到
Request header:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
Cache-Control:no-cache Cache-Control:no-store Connection:keep-alive Content-Encoding:gzip Content-Type:text/html;charset=UTF-8 Date:Fri, 05 Aug 2016 03:51:56 GMT Expires:Thu, 01 Jan 1970 00:00:00 GMT Keep-Alive:timeout=20 Pragma:no-cache Server:openresty Set-Cookie:UD=%E4%BB%8A%E5%A4%A9%E4%B8%8D%E8%B5%B0%EF%BC%8C%E6%98%8E%E5%A4%A9%E5%8D%B3%E4%BD%BF%E8%B7%91%E4%B9%9F%E4%B8%8D%E4%B8%80%E5%AE%9A%E8%B7%9F%E5%BE%97%E4%B8%8A%EF%BC%81; Domain=.csdn.net; Path=/ Set-Cookie:UserName=yanggd1987; Domain=.csdn.net; Path=/ Set-Cookie:UserInfo=RjXwn4OfICh68ZVTzEjJxlcez5O%2B8RMsVvAiTV6uo4n4q1orcuBFZz29qx%2BUZ7JPFQQivvFGwFaC97NpT%2FKhtcZ2U%2B%2BzivoNtu5nTyg717xzimpeHcoutwnMg%2F5S8ZlARzA8H48TOftvUJUB0mxylQ%3D%3D; Domain=.csdn.net; Path=/ Set-Cookie:UserNick=man8er; Domain=.csdn.net; Path=/ Set-Cookie:AU=A3E; Domain=.csdn.net; Path=/ Set-Cookie:CASTGC=TGT-63516-e4e600adR5WiJAFintPeHqNCpGRvO9w7nHBYtY5XUCc2BPCCcG-passport.csdn.net; Path=/; Secure Set-Cookie:UN=yanggd1987; Domain=.csdn.net; Expires=Sat, 05-Aug-2017 03:51:55 GMT; Path=/ Set-Cookie:UE="yanggd1987@163.com"; Version=1; Domain=.csdn.net; Max-Age=31536000; Expires=Sat, 05-Aug-2017 03:51:55 GMT; Path=/ Set-Cookie:BT=1470369115868; Domain=.csdn.net; Expires=Sat, 05-Aug-2017 03:51:55 GMT; Path=/ Set-Cookie:access-token=0bd99cf6-c5bf-4683-89b8-9d8678bebff9; Domain=.csdn.net; Path=/ Transfer-Encoding:chunked Vary:Accept-Encoding |
有以上可以看出登陆过程中有cookie
POST提交的数据:
1
2
3
4
5
|
username:XXXXXXXXX password:XXXXXXXXX lt:LT-52961-eMo02Bz4tlj3wQz4QMuO173GCIdsqE execution:e15s1 _eventId:submit |
其中username和password表示我们登陆的账户和密码,那lt、execution表示什么呢?不要急,我们看看登陆页面网站的源代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
< form id = "fm1" action = "/account/login?from=http%3A%2F%2Fmy.csdn.net%2Fmy%2Fmycsdn" method = "post" > < input id = "password" name = "password" tabindex = "2" placeholder = "输入密码" class = "pass-word" type = "password" value = "" autocomplete = "off" > < div class = "row forget-password" > < span class = "col-xs-6 col-sm-6 col-md-6 col-lg-6" > < input type = "checkbox" name = "rememberMe" id = "rememberMe" value = "true" class = "auto-login" tabindex = "4" > < label for = "rememberMe" >下次自动登录</ label > </ span > < span class = "col-xs-6 col-sm-6 col-md-6 col-lg-6 forget tracking-ad" data-mod = "popu_26" > < a href = "/account/fpwd?action=forgotpassword&service=http%3A%2F%2Fmy.csdn.net%2Fmy%2Fmycsdn" rel = "external nofollow" tabindex = "5" target = "_blank" >忘记密码</ a > </ span > </ div > <!-- 该参数可以理解成每个需要登录的用户都有一个流水号。只有有了webflow发放的有效的流水号,用户才可以说明是已经进入了webflow流程。否则,没有流水号的情况下,webflow会认为用户还没有进入webflow流程,从而会重新进入一次webflow流程,从而会重新出现登录界面。 --> < input type = "hidden" name = "lt" value = "LT-53452-VLvC2gjfxdj4jheoUJQRkIXgoDZfc3" > < input type = "hidden" name = "execution" value = "e16s1" > < input id = "username" name = "username" tabindex = "1" placeholder = "输入用户名/邮箱/手机号" value = "用户名" class = "user-name" type = "text" >< input type = "hidden" name = "_eventId" value = "submit" > < input class = "logging" accesskey = "l" value = "登 录" tabindex = "6" type = "button" > </ form > |
上面注释的内容就是说明参数lt和execution的,就是在登陆过程中webflow会动态分配一个流水号LT-53452-VLvC2gjfxdj4jheoUJQRkIXgoDZfc3,我们只用获取到这个流水号才能够进行登陆。
从上面通过chrome分析得到,登陆csdn必须有cookie并且获取到webflow分配的流水号;;并且访问时必须有user-agent,否则客户端会被屏蔽。
实现
1.由于我们的系统是centos6.5,默认使用python2.6,因此我们需要先安装python2.7并安装相关第三方模块
(1)yum安装
1
2
|
rpm -Uvh https://centos6.iuscommunity.org/ius-release.rpm yum -y install python27 python27-devel python27-pip python27-setuptools |
#安装相关第三方模块
1
2
|
pip2.7 install beautifulsoup4 pip2.7 install lxml |
(2)编译安装
安装python.2.7
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
wget https://www.python.org/ftp/python/2.7.12/Python-2.7.12.tgz tar -zxvf Python-2.7.12.tgz cd Python-2.7.12 ./configure --prefix=/usr/local/python2.7 make && make install #环境变量 vim /etc/profile export PATH=/usr/local/python2.7/bin:$PATH source /etc/profile #安装setuptools wget https://pypi.python.org/packages/46/db/baa571da945ff731f3739a119574e89b12add9b05c03842103bd641d0990/setuptools-25.1.3.tar.gz#md5=0dcb9990901cb6e9631db195d4e775a7 tar -zxvf setuptools-25.1.3.tar.gz cd setuptools-25.1.3 python2.7 setup.py install #安装pip wget https://pypi.python.org/packages/e7/a8/7556133689add8d1a54c0b14aeff0acb03c64707ce100ecd53934da1aa13/pip-8.1.2.tar.gz#md5=87083c0b9867963b29f7aba3613e8f4a tar -zxvf pip-8.1.2.tar.gz cd pip-8.1.2 python2.7 setup.py install #安装相关第三方模块 pip2.7 install beautifulsoup4 pip2.7 install lxml |
注意: 通过编译安装的pip2.7 安装lxml会报错,因此还是建议使用yum安装的pip2.7
2.代码实现
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
|
vim csdn_login.py #!/usr/bin/env python2.7 #-*- coding: utf-8 -*- import urllib import urllib2 import cookielib from bs4 import BeautifulSoup filename = 'cookie_csdn.txt' #声明一个MozillaCookieJar对象实例来保存cookie,之后写入文件 cookie = cookielib.MozillaCookieJar(filename) #利用urllib2库的HTTPCookieProcessor对象来创建cookie处理器 handler = urllib2.HTTPCookieProcessor(cookie) #通过handler来构建opener opener = urllib2.build_opener(handler) loginurl = "https://passport.csdn.net/account/login?from=http://my.csdn.net/my/mycsdn" #登陆前准备:获取lt和exection response = opener.open(loginurl) soup = BeautifulSoup(response.read(), "lxml") for input in soup.form.find_all("input"): if input.get("name") == "lt": lt = input.get("value") if input.get("name") == "execution": execution = input.get("value") #post信息 values = { "username":"用户名", "password":"密码", "lt":lt, "execution":execution, "_eventId":"submit" } postdata = urllib.urlencode(values) opener.addheaders = [("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.63 Safari/537.36")] #模拟登录,保存cookie到cookie.txt中 result = opener.open(loginurl, postdata) cookie.save(ignore_discard=True, ignore_expires=True) #登陆后我们随意跳转到博客 url = "http://blog.csdn.net/XXXXXXXXX" result = opener.open(url) |
3.运行
1
|
python2.7 csdn_login.py |
至此,当我们登陆后,可以随意指定一个页面进行登陆了。
总结
1.urllib和urllib2配合使用,因为urllib可以将post数据进行encode,而urllib2不可以
2.由于使用cookie、header等,用到了urllib2的基础库opener实现访问等操作,当然也可以使用urllib2.Request(url,data,header)等其他访问方式。
3.每个网站登录方式可能不一样,我们需要根据实际情况分析。
4.模拟登陆是我们通过实战学习python的一种方法,而不是用它来恶意攻击。
以上这篇python爬虫之模拟登陆csdn的实例代码就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持服务器之家。
原文链接:https://blog.csdn.net/yanggd1987/article/details/52127436