爬虫-模拟登陆

爬虫之模拟登陆:

  在爬取网页的过程中很多

网站是需要登陆才可以查看网页信息,然后在爬取网页,这就需要我们在爬取网页之前做一些模拟登陆的事情。如何进行模拟登陆呢?其实质是利用客户端生成的cookies,因为它里面保存着SessionID的信息,登陆之后的后续请求会携带生成后的cookies发送给服务器。而服务器则会根据Cookies判断出对应的SessionID,进而找到会话。若当前会话是有效的,则服务器就会判断当前用户已经登陆,返回请求页面信息,这样我们就可以爬取我们想获取的信息了。

这里我们使用的方法是:手动在浏览器输入用户名和密码进行登陆,然后获取浏览器里面的cookies信息,编入代码进行模拟登陆操作。

github网站为例:

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 6.1;WOW64) AppleWebKit / 537.36(KHTML, like Gecko) Chrome / 70.0.3538.110 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 taken(self):
            response = self.session.get(self,login_url,headers=self.headers)
            selector = etree.HTML(response.text)
            token = selector.xpath('//div/input[2]/@value')[0]
            return token
        def login(self,email,password):
            post_data = {
                'commit' : 'Sign in',
                'utf-8' : '√',
                '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):
                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[@value!=""]/text()')
                print(name,email)

if __name__ == "__main__":
    login = Login()
    login.login(email='email',password = 'password')
View Code

 

 

 

 

 

 

 

 

 

 

posted @ 2018-12-29 16:30  Coolc  阅读(198)  评论(0编辑  收藏  举报