首页 > 代码库 > Selenium用Python的第一个示例 (Windows系统)

Selenium用Python的第一个示例 (Windows系统)

  1. Install Python (https://www.python.org/),download the latest Python version

  2. Configure environment variables. (Example), I installed Python under /installation folder with Python 3.5.2. The path set is as follows:

    D:\installation\Python3.5.2;D:\installation\Python3.5.2\Scripts;

  3. Install pip (you may search related steps from internet to install)

    (locate to /Scripts folder, to perform easy_install pip command

    技术分享

  4. If installation success, type pip command to check

    技术分享

  5. Install selenium. To perform command pip install -U selenium

    技术分享

  6. Till now, Python and Selenium have been installed successfully, then you are able to create Python code to drive browser. Here we using Edge browser to check.

  7. Before you do, you need to download Edge driver (https://developer.microsoft.com/en-us/microsoft-edge/tools/webdriver/) and put it on Python installation foloder (D:\installation\Python3.5.2)

    技术分享

  8. from selenium import webdriver


    driver = webdriver.Edge()

    driver.get("https://www.baidu.com")

    print("width:600,height:800")

    driver.set_window_size(600,800)

    driver.quit()


  1. 查看一下源代码,看看上面这段代码是如何工作的

    首先在lib目录下有一个site-packages的文件夹,下面有一个selenium的目录

D:\installation\Python3.5.2\Lib\site-packages\selenium,selenium目录下有一个webdriver的目录,里面是支持的各个浏览器

技术分享

这个是__init__.py的代码

技术分享


从当前目录导入WebDriver类,然后给它一个别名,如Edge (对应的代码调用就是webdriver.Edge(),不然就应当写成webdriver.WebDriver())

打开WebDriver类的代码,如图所示

技术分享


有两个方法,一个是初始__init__,一个是quit,调用Edge()后就执行__init__方法,最后关闭edge时调用quit()方法

     


本文出自 “WayToGo” 博客,请务必保留此出处http://waytogo.blog.51cto.com/12732809/1908750

Selenium用Python的第一个示例 (Windows系统)