美文网首页
模拟登录(一)

模拟登录(一)

作者: mo_陌上花开 | 来源:发表于2018-07-31 09:33 被阅读0次

    Selenium是一套完整的Web应用程序测试系统,它包含了测试的录制(Selenium IDE)、编写及运行(Selenium Remote Control)和测试的并行处理(Selenium Grid)。Selenium的核心Selenium Core基于JsUnit,完全由JavaScript编写,因此可运行于任何支持JavaScript的浏览器上。与WatiN相同,Selenium也是一款同样使用Apache License 2.0协议发布的开源框架。

    使用selenium进行简单的模拟登录

    1.引入selenium package, 建立webdriver对象
    from selenium import webdriver
    sel = webdriver.Chrome()
    
    2.打开设定的url,并等待响应
    loginurl = 'http://www.daishusale.com/user/login/1'
    # open the login in page
    sel.get(loginurl)
    
    3.通过xpath找到登录框,并填入相应帐号密码,模拟点击登录
    try:
        # 找到登录框的位置,并输入账号
        sel.find_element_by_xpath("//form[@id='loginForm2']/div[@class='form-input'][1]/input[@id='number2']").send_keys('username‘)
        print('user success!')
    except:
        print('user error!')
    time.sleep(1)
    
    try:
        #找到密码框的位置,并输入密码
        sel.find_element_by_xpath("//form[@id='loginForm2']/div[@class='form-input'][2]/input[@id='password']").send_keys(’password')
        print('pw success!')
    except:
        print('pw error!')
    time.sleep(1)
    
    try:
        #找到登录按钮,模拟点击登录
        sel.find_element_by_xpath("//form[@id='loginForm2']/div[@class='form-input bottom-margin']/input[@id='btnsubmit']").click()
        print('click success!')
    except:
        print('click error!')
    time.sleep(3)
    
    4.通过对象的方法获取当前访问网站的session cookie
    # 获取session cookie 
    cookie = [item["name"] + "=" + item["value"] for item in sel.get_cookies()]
    cookiestr = ';'.join(item for item in cookie)
    print(cookiestr)
    
    5.将获取到的cookiestr存储到headers中
    # 伪造User-Agent请求头
    header = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36',
        'cookie':cookiestr
    }
    

    在接下来的操作中,我们就可以用requests库,直接进行使用了,这种方法要比使用requests模拟登录简单方便快捷

    相关文章

      网友评论

          本文标题:模拟登录(一)

          本文链接:https://www.haomeiwen.com/subject/hzbfvftx.html