温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Selenium爬虫登录生成Cookie的方法

发布时间:2021-09-09 14:41:06 来源:亿速云 阅读:194 作者:chen 栏目:编程语言

本篇内容主要讲解“Selenium爬虫登录生成Cookie的方法”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“Selenium爬虫登录生成Cookie的方法”吧!

Selenium爬虫登录生成Cookie

网站登录,本质上就是登录完成之后服务器给客户端一个凭据,这个凭据可以存在cookie里,也可以存在别的地方,客户端下次请求网页的时候带上这个凭据,服务端就会认为这个客户端是登录过的。所以对于爬虫来说,生成cookies是代理使用成为了一个必须要做的事情。

示例

安装chrome和对应driver

下载chrome对应版本的chrome deriver

下载对应版本 driver 
https://chromedriver.chromium.org/downloads

例如:

Selenium爬虫登录生成Cookie的方法

Selenium爬虫登录生成Cookie的方法

生成cookies

我们使用chrome driver来进行登录和cookie的生成

import os

import time

import zipfile

from selenium import webdriver

from selenium.common.exceptions import TimeoutException

from selenium.webdriver.common.by import By

from selenium.webdriver.support import expected_conditions as EC

from selenium.webdriver.support.ui import WebDriverWait

class GenCookies(object):

USER_AGENT = open('useragents.txt').readlines()

# 16yun 代理配置

PROXY_HOST = 't.16yun.cn' # proxy or host 亿牛云代理www.16yun.cn

PROXY_PORT = 31111 # port

PROXY_USER = 'USERNAME' # username

PROXY_PASS = 'PASSWORD' # password

@classmethod

def get_chromedriver(cls, use_proxy=False, user_agent=None):

manifest_json = """

{

"version": "1.0.0",

"manifest_version": 2,

"name": "Chrome Proxy",

"permissions": [

"proxy",

"tabs",

"unlimitedStorage",

"storage",

"<all_urls>",

"webRequest",

"webRequestBlocking"

],

"background": {

"scripts": ["background.js"]

},

"minimum_chrome_version":"22.0.0"

}

"""

background_js = """

var config = {

mode: "fixed_servers",

rules: {

singleProxy: {

scheme: "http",

host: "%s",

port: parseInt(%s)

},

bypassList: ["localhost"]

}

};

chrome.proxy.settings.set({value: config, scope: "regular"}, function() {});

function callbackFn(details) {

return {

authCredentials: {

username: "%s",

password: "%s"

}

};

}

chrome.webRequest.onAuthRequired.addListener(

callbackFn,

{urls: ["<all_urls>"]},

['blocking']

);

""" % (cls.PROXY_HOST, cls.PROXY_PORT, cls.PROXY_USER, cls.PROXY_PASS)

path = os.path.dirname(os.path.abspath(__file__))

chrome_options = webdriver.ChromeOptions()

if use_proxy:

pluginfile = 'proxy_auth_plugin.zip'

with zipfile.ZipFile(pluginfile, 'w') as zp:

zp.writestr("manifest.json", manifest_json)

zp.writestr("background.js", background_js)

chrome_options.add_extension(pluginfile)

if user_agent:

chrome_options.add_argument('--user-agent=%s' % user_agent)

driver = webdriver.Chrome(

os.path.join(path, 'chromedriver'),

chrome_options=chrome_options)

return driver

def __init__(self, username, password):

self.url = 'https://passport.weibo.cn/signin/login?entry=mweibo&r=https://m.weibo.cn/'

self.browser = self.get_chromedriver(use_proxy=True, user_agent=self.USER_AGENT)

self.wait = WebDriverWait(self.browser, 20)

self.username = username

self.password = password

def open(self):

"""

打开网页输入用户名密码并点击

:return: None

"""

self.browser.delete_all_cookies()

self.browser.get(self.url)

username = self.wait.until(EC.presence_of_element_located((By.ID, 'loginName')))

password = self.wait.until(EC.presence_of_element_located((By.ID, 'loginPassword')))

submit = self.wait.until(EC.element_to_be_clickable((By.ID, 'loginAction')))

username.send_keys(self.username)

password.send_keys(self.password)

time.sleep(1)

submit.click()

def password_error(self):

"""

判断是否密码错误

:return:

"""

try:

return WebDriverWait(self.browser, 5).until(


EC.text_to_be_present_in_element((By.ID, 'errorMsg'), '用户名或密码错误'))

except TimeoutException:

return False

def get_cookies(self):

"""

获取Cookies

:return:

"""

return self.browser.get_cookies()

def main(self):

"""

入口

:return:

"""

self.open()

if self.password_error():

return {

'status': 2,

'content': '用户名或密码错误'

}

# 如果不需要验证码直接登录成功

cookies = self.get_cookies()

return {

'status': 1,

'content': cookies

}

if __name__ == '__main__':

result = GenCookies(

username='180000000',

password='16yun',

).main()

print(result)

import osimport timeimport zipfilefrom selenium import webdriverfrom selenium.common.exceptions import TimeoutExceptionfrom selenium.webdriver.common.by import Byfrom selenium.webdriver.support import expected_conditions as ECfrom selenium.webdriver.support.ui import WebDriverWaitclass GenCookies(object):    USER_AGENT = open('useragents.txt').readlines()    # 16yun 代理配置    PROXY_HOST = 't.16yun.cn'  #  proxy or host 亿牛云代理www.16yun.cn    PROXY_PORT = 31111  # port    PROXY_USER = 'USERNAME'  # username    PROXY_PASS = 'PASSWORD'  # password        @classmethod    def get_chromedriver(cls, use_proxy=False, user_agent=None):        manifest_json = """        {            "version": "1.0.0",            "manifest_version": 2,            "name": "Chrome Proxy",            "permissions": [                "proxy",                "tabs",                "unlimitedStorage",                "storage",                "<all_urls>",                "webRequest",                "webRequestBlocking"            ],            "background": {                "scripts": ["background.js"]            },            "minimum_chrome_version":"22.0.0"        }        """        background_js = """        var config = {                mode: "fixed_servers",                rules: {                singleProxy: {                    scheme: "http",                    host: "%s",                    port: parseInt(%s)                },                bypassList: ["localhost"]                }            };        chrome.proxy.settings.set({value: config, scope: "regular"}, function() {});        function callbackFn(details) {            return {                authCredentials: {                    username: "%s",                    password: "%s"                }            };        }        chrome.webRequest.onAuthRequired.addListener(                    callbackFn,                    {urls: ["<all_urls>"]},                    ['blocking']        );        """ % (cls.PROXY_HOST, cls.PROXY_PORT, cls.PROXY_USER, cls.PROXY_PASS)        path = os.path.dirname(os.path.abspath(__file__))        chrome_options = webdriver.ChromeOptions()        if use_proxy:            pluginfile = 'proxy_auth_plugin.zip'            with zipfile.ZipFile(pluginfile, 'w') as zp:                zp.writestr("manifest.json", manifest_json)                zp.writestr("background.js", background_js)            chrome_options.add_extension(pluginfile)        if user_agent:            chrome_options.add_argument('--user-agent=%s' % user_agent)        driver = webdriver.Chrome(            os.path.join(path, 'chromedriver'),            chrome_options=chrome_options)        return driver    def __init__(self, username, password):        self.url = 'https://passport.weibo.cn/signin/login?entry=mweibo&r=https://m.weibo.cn/'        self.browser = self.get_chromedriver(use_proxy=True, user_agent=self.USER_AGENT)        self.wait = WebDriverWait(self.browser, 20)        self.username = username        self.password = password    def open(self):        """        打开网页输入用户名密码并点击        :return: None        """        self.browser.delete_all_cookies()        self.browser.get(self.url)        username = self.wait.until(EC.presence_of_element_located((By.ID, 'loginName')))        password = self.wait.until(EC.presence_of_element_located((By.ID, 'loginPassword')))        submit = self.wait.until(EC.element_to_be_clickable((By.ID, 'loginAction')))        username.send_keys(self.username)        password.send_keys(self.password)        time.sleep(1)        submit.click()    def password_error(self):        """        判断是否密码错误        :return:        """        try:            return WebDriverWait(self.browser, 5).until(                EC.text_to_be_present_in_element((By.ID, 'errorMsg'), '用户名或密码错误'))        except TimeoutException:            return False    def get_cookies(self):        """        获取Cookies        :return:        """        return self.browser.get_cookies()    def main(self):        """        入口        :return:        """        self.open()        if self.password_error():            return {                'status': 2,                'content': '用户名或密码错误'            }        # 如果不需要验证码直接登录成功        cookies = self.get_cookies()        return {            'status': 1,            'content': cookies        }if __name__ == '__main__':    result = GenCookies(        username='180000000',        password='16yun',    ).main()    print(result)

useragents.txt文件里面是随机的ua

Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2.16) Gecko/20110319 Firefox/40Mozilla/5.0 (Windows NT 6.2; rv:39.0) Gecko/20100101 Firefox/39.0Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0; QQBrowser/8.3.4769.400)Mozilla/5.0 (Windows NT 6.1; rv:39.0) Gecko/20100101 Firefox/39.0

到此,相信大家对“Selenium爬虫登录生成Cookie的方法”有了更深的了解,不妨来实际操作一番吧!这里是亿速云网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI