Python模拟登录csdn代码
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python模拟登录csdn代码相关的知识,希望对你有一定的参考价值。
#encoding: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()) 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信息 postdata = { "username":"[email protected]", "password":"xxxxxx", "lt":lt, "execution":execution, "_eventId":"submit" } postdata = urllib.urlencode(postdata) 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 cookie.save(ignore_discard=True, ignore_expires=True) #登陆后我们随意跳转到博客获取内容 url = "http://blog.csdn.net" response = opener.open(url) #读取内容保存到html文件中,方便查看 f = open(‘csdn_index.html‘, ‘w‘) f.write(response.read()); f.close() print ‘ok‘
以上是关于Python模拟登录csdn代码的主要内容,如果未能解决你的问题,请参考以下文章