python selenium cookie 登录
概要:
1、正常登录,使用selenium获取cookie;
2、保存cookie;
3、使用cookie登录。
4、python--2.7,selenium--3.4.1
步骤1
正常登录,使用selenium获取cookie。
代码如下。
handlingcookie.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2017/8/9 14:07 from selenium import webdriver if __name__ == '__main__': url = "http://demo.avactis.com/4.7.9/sign-in.php" username = "xxxxxxxxxx@gmail.com" password = "xxxxxxxxxxxx" id_username = "account_sign_in_form_email_id" id_password = "account_sign_in_form_passwd_id" css_button = ".btn.btn-primary.input_submit" driver = webdriver.Chrome() driver.get(url) driver.find_element_by_id(id_username).send_keys(username) driver.find_element_by_id(id_password).send_keys(password) driver.find_element_by_css_selector(css_button).click() with open("cookie.data", "w") as f: for cookie in driver.get_cookies(): print(cookie) f.write( str(cookie) + "\n" )
执行后,保存cookie到文件
cookie.data
{u'domain': u'.avactis.com', u'secure': False, u'value': u'GA1.2.2145942479.1502271335', u'expiry': 1502357749, u'path': u'/', u'httpOnly': False, u'name': u'_gid'} {u'domain': u'.avactis.com', u'secure': False, u'value': u'GA1.2.1002502728.1502271335', u'expiry': 1565343349, u'path': u'/', u'httpOnly': False, u'name': u'_ga'} {u'domain': u'demo.avactis.com', u'secure': False, u'value': u'71a75b89b195945b4e9a80423711167e', u'expiry': 1510047349.50336, u'path': u'/', u'httpOnly': False, u'name': u'avactis_visitor_id'} {u'domain': u'.avactis.com', u'secure': False, u'value': u'1', u'expiry': 1502271395, u'path': u'/', u'httpOnly': False, u'name': u'_gat'} {u'domain': u'demo.avactis.com', u'secure': False, u'value': u'cmljk1spe04cdhlaefhtr3s4a0', u'expiry': 1504863349.503341, u'path': u'/', u'httpOnly': False, u'name': u'CZSESSID'} {u'domain': u'demo.avactis.com', u'secure': False, u'value': u'save', u'expiry': 1502357746.463145, u'path': u'/', u'httpOnly': False, u'name': u'save_session'}
步骤2
使用cookie登录
loading_cookie_data.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2017/8/9 15:06 import time from selenium import webdriver if __name__ == '__main__': url = "http://demo.avactis.com/4.7.9" with open("cookie.data", "r") as f: lis_lines = f.readlines() driver = webdriver.Chrome() driver.get(url) for line in lis_lines: dic_line = eval(line.strip()) driver.add_cookie(dic_line) driver.refresh() time.sleep(5)
工程目录
需要注意
1、首先,打开url driver.get(url) ,然后才能添加cookie driver.add_cookie(dic_line) 。
2、handlingcookie.py中,登录后,不能点击页面上的signout,否则会导致cookie无效。
3、需要将chromedriver.exe的路径配置在环境变量中。