Python 爬虫之模拟登陆CSND

Python 爬虫之模拟登陆CSND

作者:IMyxuan

工具

基本的脚本语言是Python,虽然不敢说是最好的语言,至少是最好的之一(0.0),用模拟登陆,我们需要用到多个模块,如下:

  1. requests
  2. BeautifulSoup

requests

安装

  1. 下载源码安装
				git clone git://github.com/kennethreitz/requests.git
				cd requests
				pip install .
			
  1. pip
pip install requests

BeautifulSoup

介绍

Beautiful Soup 是一个可以从HTML或XML文件中提取数据的Python库.它能够通过你喜欢的转换器实现惯用的文档导航,查找,修改文档的方式.Beautiful Soup会帮你节省数小时甚至数天的工作时间.

安装

easy_install beautifulsoup4
pip install beautifulsoup4

使用

				from bs4 import BeautifulSoup
				soup = BeautifulSoup(open("index.html"))
				soup = BeautifulSoup("<html>data</html>", 'lxml')
			

说明

requests主要是为了利用requests的高级会话机制,requests的会话对象可以让我们跨请求保持某些参数,比如cookies, headers等,

会话对象让你能够跨请求保持某些参数。它也会在同一个 Session 实例发出的所有请求之间保持 cookie, 期间使用 urllib3 的 connection pooling 功能。所以如果你向同一主机发送多个请求,底层的 TCP 连接将会被重用,从而带来显著的性能提升。

而BeautifulSoup主要是方便解析HTML源码,从中获取请求需要的一些参数

完整代码

				# -*- coding: UTF-8 -*-
				from bs4 import BeautifulSoup
				import requests
				s = requests.Session()
				class CSDN:
				def __init__(self, username, password):
				self.username = username
				self.password = password
				self.login_url = 'https://passport.csdn.net/account/login'
				self.headers = {
				'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebK'
				'it/537.36 (KHTML, like Gecko) Chrome/61.0.3163.1'
				'00 Safari/537.36 OPR/48.0.2685.52',
				'Referer': 'http://my.csdn.net/my/mycsdn'
				}
				def login(self):
				params = {
				'from': 'http://my.csdn.net/my/mycsdn'
				}
				html = s.get(self.login_url, params=params, headers=self.headers)
				soup = BeautifulSoup(html.content, 'lxml')
				lt = soup.select('input[name="lt"]')[0].get('value')
				execution = soup.select('input[name="execution"]')[0].get('value')
				event_id = soup.select('input[name="_eventId"]')[0].get('value')
				data = {
				'username': self.username,
				'password': self.password,
				'rememberMe': 'true',
				'lt': lt,
				'execution': execution,
				'_eventId': event_id
				}
				r = s.post(self.login_url, data=data)
				self.headers['Referer'] = 'http://passport.csdn.net/account/login?from=http%3A%2F%2Fmy.csdn.net%2Fmy%2Fmycsdn'
				resp = s.get('http://my.csdn.net/my/mycsdn', headers=self.headers)
				print(resp.text)
				username = input('请输入账号:')
				password = input('请输入密码:')
				cs = CSDN(username, password)
				cs.login()
			

项目地址:  模拟京东登录

End.

转载请注明来自36大数据(36dsj.com): 36大数据 » Python 爬虫之模拟登陆CSND

随意打赏

python爬虫
提交建议
微信扫一扫,分享给好友吧。