1.摘要:

Selenium是一个开源的和携带型的自动化软体测试工具,用于测试Web应用程序有能力在不同的浏览器和操作系统运行。Selenium不是一个单一的工具,而是一套工具,帮助测试者更有效地基于Web的应用程序的自动化。

我们这里用到的

python:python3.6

操作系统:archlinux

相关库:

time

requests

logging

2.Selenium和Python的安装和配置

Selenium相关文档可参考

Selenium Python Bindings 1. Installation - Selenium Python Bindings 2 documentation

Python相关文档可参考python官网

Welcome to Python.org

3.导入相关库

import time
from selenium import webdriver
import requests
import logging

4.分析登录页面

(登录 - 开源中国社区)

发现我们只需要关注三个地方,手机/邮箱这个输入框,密码框,登录按钮。利用chrome的检查功能,检查这三个地方得:

手机/邮箱 <input type="text" id="userMail" value="" placeholder="手机/邮箱" class="">

密码框 <input type="password" id="userPassword" value="" placeholder="请输入密码">

登录按钮 <button type="button" class="btn btn-green block btn-login error">登录</button>

5.编写Selenium自动化登录操作

username = browser.find_element_by_id("userMail")
username.clear()
username.send_keys(account)
psd = browser.find_element_by_id("userPassword")
psd.clear()
psd.send_keys(password)
commit = browser.find_element_by_tag_name("button")
commit.click()

关于Selenium的定位方法(根据名字就应该能猜出来吧,我就不做过多解释了)

  • find_element_by_id
  • find_element_by_name
  • find_element_by_xpath
  • find_element_by_link_text
  • find_element_by_partial_link_text
  • find_element_by_tag_name
  • find_element_by_class_name
  • find_element_by_css_selector

6.获取Cookie

for elem in browser.get_cookies():
cookie+=elem["name"]+"="+ elem["value"]+"; "
if len(cookie) > 0:
logger.warning("获取cookie成功: %s" % account)
cookies.append(cookie)
continue

7.访问问答页面,判断是否成功登录

因为没有登陆的话,无法对某人进行提问且会进入登录页面,所以利用这个进行测试,是否成功登录。。

headers={
Accept:*/*,
Accept-Encoding:gzip, deflate, br,
Accept-Language:zh-CN,zh;q=0.8,
Cookie:cookies[0],
User-Agent:Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.96 Safari/537.36,
hd-token:hello,
X-Requested-With:XMLHttpRequest
}
req=requests.Session()
t=req.get(url=https://www.oschina.net/question/ask?user=3392136,headers=headers)

码云: nanxun/monidenglukaiyuanzhongguo - 码云 - 开源中国

github : github.com/nanxung/Sele

推荐阅读:

相关文章