您的位置:首页 > 编程语言 > Python开发

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

2017-07-05 23:15 405 查看
摘要: 人生苦短,我用python.
life is short,I use python.

1.摘要:

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

我们这里用到的

python:python3.6

操作系统:archlinux

相关库:

time

requests

logging

2.Selenium和Python的安装和配置

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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Python Selenium Requests