用python自动登录iteye
程序员文章站
2023-12-24 08:23:51
...
需要beautifulsoup插件,python版本3
# -*- coding:utf-8 -*- from bs4 import BeautifulSoup import urllib import urllib.request import http.cookiejar import string import re referurl="http://www.iteye.com"# hosturl = "http://www.iteye.com/login" #自己填写 ##########################session获取 #设置一个cookie处理器,它负责从服务器下载cookie到本地,并且在发送请求时带上本地的cookie cj = http.cookiejar.LWPCookieJar() cookie_support = urllib.request.HTTPCookieProcessor(cj) opener = urllib.request.build_opener(cookie_support, urllib.request.HTTPHandler) urllib.request.install_opener(opener) #构造header,一般header至少要包含一下两项。这两项是从抓到的包里分析得出的。 headers = {'User-Agent' : 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:43.0) Gecko/20100101 Firefox/43.0', 'Referer' : hosturl} #打开登录主页面(他的目的是从页面下载cookie,这样我们在再送post数据时就有cookie了,否则发送不成功) request = urllib.request.Request(hosturl, None, headers) response = urllib.request.urlopen(request) htmldata = response.read() html_doc=htmldata.decode('utf-8') #print(htmldata.decode('utf-8')) ##########################session获取完毕,以下的操作,在一个session中进行。 soup = BeautifulSoup(html_doc,"html.parser") tokenfind=soup.find('input', {'name': 'authenticity_token'}).get('value')#一个验证串,同一个session周期内,不会改变 print(tokenfind) username=input('输入用户名:'); passinput=input('输入密码:'); #构造Post数据,从抓的包里分析得出的。 postData = {'name': username,'password':passinput,'authenticity_token':tokenfind} postData = urllib.parse.urlencode(postData).encode('utf-8') headers = {'User-Agent' : 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:43.0) Gecko/20100101 Firefox/43.0', 'Referer' : referurl} request = urllib.request.Request(hosturl, postData, headers) #print(request) response = urllib.request.urlopen(request) text = response.read() print(text) print("------------------------login success--------------------------") request = urllib.request.Request(referurl+'/admin', None, headers) response = urllib.request.urlopen(request) text = response.read() print(text.decode('utf-8'))