data不用考虑那么多参数:import requests
import re
def login():
session = requests.session()
session.headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:91.0) Gecko/20100101 Firefox/91.0'}
login_url = 'https://github.com/login'
r = session.get(login_url)
token = re.findall('name="authenticity_token" value="(.*?)"/>', r.text)[1]
print(token)
post_url = 'https://github.com/session'
data = {
'commit': 'Sign in',
'utf8': '✓',
'authenticity_token': token,
'login': 'email',
'password': 'password'
}
print(data)
session.post(post_url, data=data)
logined_url = 'https://github.com/settings/profile'
r = session.get(logined_url)
with open('github.html', 'w') as f:
f.write(r.text)
if __name__ == '__main__':
login()
别人的案例import requests
from lxml import etree
class Login(object):
def __init__(self):
self.headers = {
'Referer': 'https://github.com/',
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36',
'Host': 'github.com'
}
self.login_url = 'https://github.com/login'
self.post_url = 'https://github.com/session'
self.logined_url = 'https://github.com/settings/profile'
self.session = requests.Session()
def token(self):
response = self.session.get(self.login_url, headers=self.headers)
selector = etree.HTML(response.text)
token = selector.xpath('//input[1]/@value')[0]
return token
def login(self, email, password):
post_data = {
'commit': 'Sign in',
'utf8': '✓',
'authenticity_token': self.token(),
'login': email,
'password': password
}
response = self.session.post(self.post_url, data=post_data, headers=self.headers)
if response.status_code == 200:
self.dynamics(response.text)
response = self.session.get(self.logined_url, headers=self.headers)
if response.status_code == 200:
self.profile(response.text)
def dynamics(self, html):
selector = etree.HTML(html)
dynamics = selector.xpath('//div[contains(@class, "news")]//div[contains(@class, "alert")]')
for item in dynamics:
dynamic = ' '.join(item.xpath('.//div[@class="title"]//text()')).strip()
print(dynamic)
def profile(self, html):
selector = etree.HTML(html)
name = selector.xpath('//input[@id="user_profile_name"]/@value')[0]
email = selector.xpath('//select[@id="user_profile_email"]/option[2]/@value')[0]
# 能正确显示自己账号的信息即为成功
print(name, email)
if __name__ == "__main__":
login = Login()
login.login(email='账号', password='密码')
|