#!/usr/bin/env python
# encoding: utf-8
import requests
from headers import headers
from lxml import html
from config import *
class Login(object):
def __init__(self):
headers["Referer"] = 'https://github.com/'
headers["Host"] = 'github.com'
self.login_url="https://github.com/login"
self.post_url="https://github.com/session"
self.headers=headers
self.session=requests.Session()
def get_token(self):
response=self.session.get(self.login_url,timeout=5)
if response.status_code==requests.codes.ok:
root = html.fromstring(response.text)
token = root.xpath("//input[@name='authenticity_token']/@value")[0]
if token:
return token
return False
def lgoin(self):
token=self.get_token()
if token:
data = {"commit": "Sign in", "utf8": "✓", "authenticity_token": token, "login":LOGIN_ID ,
"password": PASS_WORD}
response = self.session.post(url=self.post_url, headers=headers, data=data, timeout=15)
print(response.text)
else:
print("获取token失败,登录失败")
if __name__=="__main__":
Login().lgoin()
#其中authenticity_token的值,位于一个隐藏的input标签中,另外headers需要传入的信息不止要有ua,还有
headers["Referer"] = 'https://github.com/'
headers["Host"] = 'github.com'
转载于:https://www.cnblogs.com/c-x-a/p/9023145.html
相关资源:python requests模拟登陆github的实现方法