Python 爬虫之模拟登陆CSND[转]
工具 基本的脚本语言是Python,虽然不敢说是最好的语言,至少是最好的之一(0.0),用模拟登陆,我们需要用到多个模块,如下: 1、requests 2、BeautifulSoup requests 安装 下载源码安装 gitclonegit://github.com/kennethreitz/requests.git cdrequests pipinstall. pip pipinstallrequests BeautifulSoup 介绍 Beautiful Soup 是一个可以从HTML或XML文件中提取数据的Python库.它能够通过你喜欢的转换器实现惯用的文档导航,查找,修改文档的方式.Beautiful Soup会帮你节省数小时甚至数天的工作时间. 安装 easy_installbeautifulsoup4 pipinstallbeautifulsoup4 使用 frombs4importBeautifulSoup soup=BeautifulSoup(open("index.html")) soup=BeautifulSoup("data",'lxml') 说明 requests主要是为了利用requests的高级会话机制,requests的会话对象可以让我们跨请求保持某些参数,比如cookies, headers等 会话对象让你能够跨请求保持某些参数。它也会在同一个 Session 实例发出的所有请求之间保持 cookie, 期间使用 urllib3 的 connection pooling 功能。所以如果你向同一主机发送多个请求,底层的 TCP 连接将会被重用,从而带来显著的性能提升 而BeautifulSoup主要是方便解析HTML源码,从中获取请求需要的一些参数 完整代码 #-*-coding:UTF-8-*- frombs4importBeautifulSoup importrequests s=requests.Session() classCSDN: 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(WindowsNT10.0;Win64;x64)AppleWebK' 'it/537.36(KHTML,likeGecko)Chrome/61.0.3163.1' '00Safari/537.36OPR/48.0.2685.52', 'Referer':'http://my.csdn.net/my/mycsdn' } deflogin(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() 原文链接:https://segmentfault.com/a/1190000012013734