selenium2+python_用cookie实现自动登录(百度首页为例)
2018-02-01 16:51
1156 查看
最近在学selenium webdriver,看书的过程中发现用cookie处理自动登录,所以研究了一下如何登录百度首页。过程很简单,先手动登录获取了cookies,然后保存得到的cookies,再开始写自动登录的代码。(由于有验证码,必须的这么做啊,高级的验证码处理方式我还不会,高手请绕过)。
获取cookies
代码如下:
得到的cookies是一个list,里面有几个字典元素,类似下图:
自动登录
获取cookies
代码如下:
# coding:utf-8 from selenium import webdriver from selenium.common.exceptions import NoSuchElementException import time def login(): # 手动登录获取cookies driver = webdriver.Chrome() driver.get("https://pan.baidu.com/") driver.implicitly_wait(10) # 如果不等待,下面的语句会出现找不到元素的错误 login=driver.find_element_by_id("TANGRAM__PSP_4__footerULoginBtn") print login.get_attribute("innerHTML") login.click() username = "********" password = "********" driver.find_element_by_css_selector("#TANGRAM__PSP_4__userName").clear() driver.find_element_by_css_selector("#TANGRAM__PSP_4__userName").send_keys(username) driver.find_element_by_css_selector("#TANGRAM__PSP_4__password").send_keys(password) driver.find_element_by_css_selector("#TANGRAM__PSP_4__submit").click() time.sleep(10) # 留充足的时间手动输入验证码 try: # 查找登录按钮,如果找不到,抛出异常 driver.find_element_by_css_selector("#TANGRAM__PSP_4__submit").click() except NoSuchElementException, msg: print msg time.sleep(5) cookies = driver.get_cookies() print cookies print driver.title title = driver.title # 返回的title为unicode类型,下面比较时应该也应与unicode类型比较 user = driver.find_element_by_class_name("user-name") username = user.get_attribute("innerHTML") #下面的代码是自己测试是否登录成功的 try: if title == u'百度网盘-全部文件' and username == u'*****': # u定义了一个unicode类型 print "登录成功" else: raise AssertionError("登录失败") except AssertionError, msg: print msg if __name__ == "__main__": login()
得到的cookies是一个list,里面有几个字典元素,类似下图:
自动登录
from selenium import webdriver import time driver= webdriver.Chrome() driver.get("https://pan.baidu.com/") login=driver.find_element_by_css_selector("#u1 > a.lb") print login.get_attribute("innerHTML") login.click() time.sleep(5) userlogin=driver.find_element_by_css_selector("#TANGRAM__PSP_10__footerULoginBtn") userlogin.click() cookieslist=[] #把获取到的cookie复制过来就行了 for cookie in cookieslist: #遍历添加cookie driver.add_cookie(cookie) time.sleep(5) driver.get("https://www.baidu.com") time.sleep(5)
相关文章推荐
- Selenium+phantomJS+Python 操作cookie实现自动登录(以音悦台为例)
- selenium+python实现自动登录脚本
- python+cookielib实现批量利用账号和密码自动获取新浪微博登录cookie
- Python Selenium Cookie 绕过验证码实现登录示例代码
- [Python爬虫] Selenium实现自动登录163邮箱和Locating Elements介绍
- Python使用selenium实现网页用户名 密码 验证码自动登录功能
- [Python爬虫] Selenium实现自动登录163邮箱和Locating Elements介绍
- Python实现Selenium实现自动登录CSDN
- Python Selenium实现自动登录163邮箱
- python+selenium实现京东自动登录及秒杀功能
- Python Selenium Cookie 绕过验证码实现登录
- python实现百度、CSDN、淘宝、人人自动登录(第一季)
- python3模拟百度登录并实现百度贴吧签到示例分享(百度贴吧自动签到)
- Python selenium实现微博自动登录的示例代码
- python+selenium实现登录账户后自动点击的示例
- python3模拟百度登录并实现百度贴吧签到示例分享(百度贴吧自动签到)
- python pyqt4 qtwekit 实现百度自动登录领米粒
- python+selenium实现登录账户后自动点击
- Python+Selenium实现新浪微博自动登录
- Python爬虫 Selenium实现自动登录163邮箱和Locating Elements介绍