简体   繁体   English

Selenium,使用Python,如何简化脚本,以便可以从其他python脚本运行它们?

[英]Selenium, with Python, how to simplify scripts so that I can run them from other python scripts?

I'm having some trouble figuring out how to take out what is not necessary in a selenium strip and package it in such a way that I can call it from another script.. I am having trouble understanding what is going on with this, as I don't get where the unit testint parts are coming from... ideally if I could just separate this into a function that I could call that would be idea, thanks for any advice. 我在弄清楚如何取出硒带中不需要的东西并将其打包以便可以从另一个脚本中调用它的方式时遇到了一些麻烦。我不知道单位testint部件的来源...理想情况下,如果我可以将其分离为一个可以调用的函数,那将是个主意,谢谢您的任何建议。

(AND, yes i do need selenium, I kindly ask that you please don't suggest alternatives as I am going to be using selenium for a lot of things so I need to figure this out) (而且,是的,我确实需要硒,所以请您不要提出替代方案,因为我将在很多事情上使用硒,因此我需要弄清楚这一点)

This is just a basic demo script: 这只是一个基本的演示脚本:

from selenium import selenium

import unittest



class TestGoogle(unittest.TestCase):

    def setUp(self):

        self.selenium = selenium("localhost", \

            4444, "*firefox", "http://www.bing.com")

        self.selenium.start()



    def test_google(self):

        sel = self.selenium

        sel.open("http://www.google.com/webhp")

        sel.type("q", "hello world")

        sel.click("btnG")

        sel.wait_for_page_to_load(5000)

        self.assertEqual("hello world - Google Search", sel.get_title())



    def tearDown(self):

        self.selenium.stop()



if __name__ == "__main__":

    unittest.main()

What I would recommend is to make functions in your other script that have as an argument a reference to the test case. 我建议您在其他脚本中使用作为对测试用例的引用作为参数的函数。 That way, your functions could fail the test case if something does not go right. 这样一来,如果某些操作不正确,您的功能可能会使测试用例失败。 Like so (to search google for a string and check the title): 像这样(在google中搜索字符串并检查标题):

def search_s(utest, in_str):
  s = utest.selenium
  s.type('q', in_str)
  s.click('btnG')
  s.wait_for_page_to_load('30000')
  utest.assertEqual("%s - Google Search" % (in_str,), s.get_title())

Then, in your test case, call it like this: 然后,在您的测试用例中,按以下方式调用它:

def test_google(self):
  s.open('/')
  search_s(self, "hello world")

You can then make libraries of these types of methods, allowing you to mix-and-match pieces of your tests. 然后,您可以创建这些类型的方法的库,从而允许您混合和匹配测试的各个部分。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM