selenium+python实现自动化登录的方法

yipeiwu_com7年前Python基础

Selenium Python 提供了一个简单的API 便于我们使用 Selenium WebDriver编写 功能/验收测试。 通过Selenium Python的API,你可以直观地使用所有的 Selenium WebDriver 功能 。Selenium Python提供了一个很方便的接口来驱动 Selenium WebDriver , 例如Firefox、Chrome、Ie,以及Remote,目前支持的python版本有2.7或3.2以上.

selenium 可以自动化测试、抢票、爬虫等工作。初次了解,现在模拟登录百度——即自动打开浏览器、自动输入账号密码并提交进行登录。

工作需要实现一个微博自动登录的操作,在网上差了一些资料,决定使用selenium+python实现

selenium 是一个web的自动化测试工具,主流一般配合java或者python使用,我这里使用的是python,可支持的浏览器基本包括所有主流浏览器IE、Mozilla Firefox、Google Chrome。

安装过程不再赘述,但是后续使用时,发现很多报错与版本兼容性有关,因此这里列出可用的版本搭配:

python2.7

selenium3.0.2

火狐驱动geckodriver.exe  版本v0.14.0  (使用高版本会出现异常报错)

火狐浏览器52.0.2 (32 位)  (版本太低或53的最新版本,都会报错)

#encoding=utf-8
from selenium import webdriver 
import time 
import os

#模拟登陆weibo 

def getCookies(weibo):
  """ 获取Cookies """
  cookies = []
  driver = webdriver.Firefox()
  time.sleep(3)  #sleep一下,否则有可能报错
  driver.get("https://weibo.com/login/")
  #cur_path=os.getcwd()
  #fileSuc = open(cur_path+"/login.html", 'w')
  #fileSuc.write(driver.page_source)
  #用户名 密码 
  elem_user = driver.find_element_by_xpath('//input[@id="loginname"]') 
  elem_user.send_keys('*****@163.com') #浏览器版本不匹配的时候这里可能报错
  elem_pwd = driver.find_element_by_xpath('//input[@type="password"]')
  elem_pwd.send_keys('*****')
  
  commit = driver.find_element_by_xpath('//a[@node-type="submitBtn"]')
  commit.click()
  time.sleep(3)
  #fileSuc1 = open(cur_path+"/weibo2.html", 'w')
  #fileSuc1.write(driver.page_source)
  #print driver.title 
  #登录成功后获取cookie
  cookie = {}
  if "微博-随时随地发现新鲜事" in driver.title:
    for elem in driver.get_cookies():
      cookie[elem["name"]] = elem["value"]
    if len(cookie) > 0:
      logger.warning("Get Cookie Successful: %s" % account)
      cookies.append(cookie)
      continue
  else:
    logger.warning("Get Cookie Failed: %s!" % account)
  
  driver.close() 
  driver.quit() 
  return cookies

cookies = getCookies(myWeiBo)
print cookies
logger.warning("Get Cookies Finish!( Num:%d)" % len(cookies))

find_element_by_xpath用来定位控件的位置,定位不到的时候,可以把网页的代码保存下来看看是否有对应的控件,如果是安全控件或者登录在js里实现,这种方法是获取不到的。

另外还有find_element_by_name、find_element_by_id的方法,但是我使用的时候出现找不到情况,怀疑是浏览器版本不匹配的原因。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

下载糗事百科的内容_python版

复制代码 代码如下:#coding:utf-8 import urllib.request import xml.dom.minidom import sqlite3 import th...

python实现可变变量名方法详解

如果要写一个程序,让x1为1,x2为2,然后直到x100为100,你会怎么做? 在C这种静态语言里,变量名这个标识符实际上会被编译器直接翻译成内存地址,所以除了手动设置每个变量的值以外,...

TensorFlow实现iris数据集线性回归

TensorFlow实现iris数据集线性回归

本文将遍历批量数据点并让TensorFlow更新斜率和y截距。这次将使用Scikit Learn的内建iris数据集。特别地,我们将用数据点(x值代表花瓣宽度,y值代表花瓣长度)找到最优...

python 单线程和异步协程工作方式解析

在python3.4之后新增了asyncio模块,可以帮我们检测IO(只能是网络IO【HTTP连接就是网络IO操作】),实现应用程序级别的切换(异步IO)。注意:asyncio只能发tc...

Python 取numpy数组的某几行某几列方法

Python 取numpy数组的某几行某几列方法

直接分析,如原矩阵如下(1):   (1) 我们要截取的矩阵(取其一三行,和三四列数据构成矩阵)为如下(2):   (2) 错误分析: 取 C 的1 3行...