Python + Selenium网页自动化测试

导言:B/S架构落败了,C/S架构兴起,各种APP,吃饭有美团外卖、饿了么、百度外卖;坐车有滴滴打车、Uber,快的打车;但是这些APP还是需要WEB后台进行数据统计与整理。

1.用selenium做网页自动化步骤:

1)环境搭建

2)selenium IDE将需要自动化的web处进行编译,对于初学者省下很大的功夫

3)将录制的脚本导出Python文件

4)修改Python文件,将其作为自己的自动化web测试脚本

5)不断的修改添加测试模块

【备注】

模拟操作:

agent=”Mozilla/5.0 (X11; U; Linux i686 (x86_64); zh-CN; rv:1.9.1.2)Gecko/20090729 Firefox/3.5.2”
s = requests.Session()
s.headers.update({‘User-Agent’: agent})

下面展示魔线网登陆,查看个人中心及查看发表动态详情

1.selenium IDE录制脚本
将录制的脚本按python语言导出

2.修改脚本

# -*- coding: utf-8 -*-
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import Select
from selenium.common.exceptions import NoSuchElementException
from selenium.common.exceptions import NoAlertPresentException
import unittest, time, re

class MoxianSelenium(unittest.TestCase):
    def setUp(self):
        self.driver = webdriver.Firefox()
        self.driver.implicitly_wait(30)
        self.base_url = "http://moxian.com/"
        self.verificationErrors = []
        self.accept_next_alert = True

    def test_moxian_selenium(self):
        driver = self.driver
        driver.get(self.base_url + "/")
        driver.find_element_by_link_text("Login").click()
        driver.find_element_by_link_text("Mobile Login").click()
        driver.find_element_by_id("txtAreaCode").clear()
        driver.find_element_by_id("txtAreaCode").send_keys("86")
        driver.find_element_by_id("txtMobliUsername").clear()
        driver.find_element_by_id("txtMobliUsername").send_keys("13133847086")
        driver.find_element_by_id("txtMobliPwd").clear()
        driver.find_element_by_id("txtMobliPwd").send_keys("123456")
        driver.find_element_by_css_selector("#btnLogin > span").click()
        driver.find_element_by_css_selector("#user_name > img").click()
        driver.find_element_by_css_selector("a.mopromo").click()

    def is_element_present(self, how, what):
        try:
            self.driver.find_element(by=how, value=what)
        except NoSuchElementException, e:
            return False
        return True

    def is_alert_present(self):
        try:
            self.driver.switch_to_alert()
        except NoAlertPresentException, e:
            return False
        return True

    def close_alert_and_get_its_text(self):
        try:
            alert = self.driver.switch_to_alert()
            alert_text = alert.text
            if self.accept_next_alert:
                alert.accept()
            else:
                alert.dismiss()
            return alert_text
        finally: self.accept_next_alert = True

    def tearDown(self):
        self.driver.quit()
        self.assertEqual([], self.verificationErrors)

if __name__ == "__main__":
    unittest.main()

你可能感兴趣的:(python,selenium,自动化)