爬虫-模拟登陆

爬虫之模拟登陆:

  在爬取网页的过程中很多

网站是需要登陆才可以查看网页信息,然后在爬取网页,这就需要我们在爬取网页之前做一些模拟登陆的事情。如何进行模拟登陆呢?其实质是利用客户端生成的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

 

 

 

 

 

 

 

 

 

 

转载于:https://www.cnblogs.com/dragon-123/articles/10196722.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值