什么是cookie:
有些网站有爬虫机制,目标网站为了避免一个IP下大量用户多次访问,就会限制访问IP。当访问目标网站的时候,需要登录的时候,cookies就是保存您的登录信息的,避免下次重复登录。Cookie其实就是浏览器缓存。
保存cookies的理由:
大部分网站在采集的时候,需要登录,必须保证您在登陆的情况下采集到数据,这时候就需要保存cookies,通过cookie进行登陆来进行业务采集。
cookie最好是登陆获取的,一般访客的cookie,对方限制会比较严格,可以控制一个地区新访客的访问频率。另外反爬统计的js也要分析下,是不是做了机器人判断,有没有做窗口分辨率判断
在一般情况下,使用Cookie方式进行登陆信息的保存。比如在爬虫业务的登录中,如果没有Cookie,登录目标网站的话,如果需要访问该网站的其它页面时,仍然会是未登录状态。如果有了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 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)
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/53348.html