selenium+pthon之一----环境搭建与脚本实例

一、安装selenium的环境

1.如何安装

1)在cmd窗口输入安装指令:pip install selenium,直到安装成功(安装目录在E:\python\Lib\site-packages 所有selenium开头的文件,python所有的第三方工具都是在这个目录里)。

2)验证:

     >python

 >from selenium import webdriver

 >webdriver.Firefox()

   确保电脑上安装了Firefox浏览器,如果能正常启动Firefox则说明安装成功。

3)下载相应的浏览器驱动放到python根目录

4)查看selenium版本号:pip show selenium

 

 2.执行了2个实例:

1)打开某个网页并查找内容

from selenium import webdriver
from selenium.webdriver.common.keys import Keys

driver = webdriver.Firefox()
driver.get("http://www.python.org")
assert "Python" in driver.title
elem = driver.find_element_by_name("q")
print(elem)
elem.clear()
elem.send_keys("pycon")
elem.send_keys(Keys.RETURN)
assert "No results found." not in driver.page_source
driver.close()

 

(2)使用unittest框架执行用例

 import unittest
from selenium import webdriver
from selenium.webdriver.common.keys import Keys

class PythonOrgSearch(unittest.TestCase):

    def setUp(self):
        self.driver = webdriver.Firefox()

    def test_search_in_python_org(self):
        driver = self.driver
        driver.get("http://www.python.org")
        self.assertIn("Python",driver.title)
        elem = driver.find_element_by_name("q")
        elem.send_keys("pycon")
        elem.send_keys(Keys.RETURN)
        assert "NO results found." not in driver.page_source

    def tearDown(self):
        self.driver.close()

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

posted @ 2019-03-29 11:18  山里姑娘  阅读(168)  评论(0编辑  收藏  举报