Selenium+Python对开源中国官网进行模拟登陆

1.摘要:css

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

咱们这里用到的python

python:python3.6linux

操做系统:archlinuxgit

相关库:github

timeweb

requestschrome

logging浏览器

2.Selenium和Python的安装和配置cookie

Selenium相关文档可参考

Selenium Python Bindings http://selenium-python.readthedocs.io/installation.html#introduction

Python相关文档可参考python官网

https://www.python.org/

3.导入相关库

import time
from selenium import webdriver
import requests
import logging

4.分析登陆页面

(https://www.oschina.net/home/login?goto_page=https%3A%2F%2Fwww.oschina.net%2F)

发现咱们只须要关注三个地方,手机/邮箱这个输入框,密码框,登陆按钮。利用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)
码云https://git.oschina.net/nanxun/monidenglukaiyuanzhongguo.git
github https://github.com/nanxung/Selenium-Python-.git
相关文章
相关标签/搜索