本页代码可以在这里下载。
首先模拟登录github,链接是http://www.github.com/login
首先观察请求,提交一个from data 其中包括5个参数,其中第三个不明确代表什么,所以猜测可能是一个加密参数。
我们清空cookies再访问界面,会发现源码中可以找到该参数,所以我们可以获取该参数然后构成表单数据。

我们首先可以发现,返回的源码是登录之后的界面,可以看到用户名。

这里使用session,可以保存的cookies,然后使用cookies访问别的界面,我们再获取到session后访问资料修改界面把用户名和博客地址爬取下来,观察用户名和博客地址并找到对应的XPath语句。
程序输出成功:

 
源码:

# -*- coding:utf-8 -*-
import requests
from lxml import etree
class Login():
    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('//div//input[2]/@value')
        return token
    def login(self, email, password):
        post_data = {
            'commit': 'Sign in',
            'utf8': '✓',
            'authenticity_token': self.token()[0],
            'login': email,
            'password': password
        }
        self.session.post(self.post_url, data=post_data, headers=self.headers)
        response = self.session.get(self.logined_url, headers=self.headers)
        if response.status_code == 200:
            self.profile(response.text)
    def profile(self, html):
        selector = etree.HTML(html)
        name = selector.xpath('//*[@id="user_profile_name"]/@value')[0]
        email = selector.xpath('//*[@id="user_profile_blog"]/@value')[0]
        print(name, '\n', email)
if __name__ == "__main__":
    login = Login()
    login.login(email='359366783@qq.com', password='000000')

0 条评论

发表回复

Avatar placeholder

您的电子邮箱地址不会被公开。 必填项已用 * 标注