zoukankan      html  css  js  c++  java
  • selenium+python实现自动化登录

    工作需要实现一个微博自动登录的操作,在网上差了一些资料,决定使用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的最新版本,都会报错)

     1 #encoding=utf-8
     2 from selenium import webdriver  
     3 import time  
     4 import os
     5 
     6 #模拟登陆weibo  
     7 
     8 def getCookies(weibo):
     9     """ 获取Cookies """
    10     cookies = []
    11     driver = webdriver.Firefox()
    12     time.sleep(3)   #sleep一下,否则有可能报错
    13     driver.get("https://weibo.com/login/")
    14     #cur_path=os.getcwd()
    15     #fileSuc = open(cur_path+"/login.html", 'w')
    16     #fileSuc.write(driver.page_source)
    17     #用户名 密码  
    18     elem_user = driver.find_element_by_xpath('//input[@id="loginname"]') 
    19     elem_user.send_keys('*****@163.com') #浏览器版本不匹配的时候这里可能报错
    20     elem_pwd = driver.find_element_by_xpath('//input[@type="password"]')
    21     elem_pwd.send_keys('*****')
    22     
    23     commit = driver.find_element_by_xpath('//a[@node-type="submitBtn"]')
    24     commit.click()
    25     time.sleep(3)
    26     #fileSuc1 = open(cur_path+"/weibo2.html", 'w')
    27     #fileSuc1.write(driver.page_source)
    28     #print driver.title  
    29     #登录成功后获取cookie
    30     cookie = {}
    31     if "微博-随时随地发现新鲜事" in driver.title:
    32         for elem in driver.get_cookies():
    33             cookie[elem["name"]] = elem["value"]
    34         if len(cookie) > 0:
    35             logger.warning("Get Cookie Successful: %s" % account)
    36             cookies.append(cookie)
    37             continue
    38     else:
    39         logger.warning("Get Cookie Failed: %s!" % account)
    40     
    41     driver.close()  
    42     driver.quit()  
    43     return cookies
    44 
    45 cookies = getCookies(myWeiBo)
    46 print cookies
    47 logger.warning("Get Cookies Finish!( Num:%d)" % len(cookies))
    find_element_by_xpath用来定位控件的位置,定位不到的时候,可以把网页的代码保存下来看看是否有对应的控件,如果是安全控件或者登录在js里实现,这种方法是获取不到的。
    另外还有find_element_by_name、find_element_by_id的方法,但是我使用的时候出现找不到情况,怀疑是浏览器版本不匹配的原因。

  • 相关阅读:
    使用DataList进行ItemDataBound时出来重复绑定
    往一个数据添加另外一个数据表里面的数据
    在ServU配置ODBC过程记录(一)
    在RowDeleting中GridViewDeleteEventArgs e的RowIndex获得值错误的问题
    在Master母版页中通过FindControl()方法获取服务器控件
    经典的间隔时间滚动新闻(图片),可控制滚动
    为枚举类型添加描述信息 this 扩展 泛型约束 位运算[转]
    SQL Server 获取插入记录后的ID(自动编号)
    Shapes
    CSSFriendlyAdapter 的一个Bug
  • 原文地址:https://www.cnblogs.com/taurusfy/p/7007014.html
Copyright © 2011-2022 走看看