跳转到主要内容

Selenium WebDriver的官方Python绑定

项目描述

介绍

Python语言绑定Selenium WebDriver。

selenium包用于从Python自动化网页浏览器交互。

主页:

https://selenium.net.cn

GitHub:

https://github.com/SeleniumHQ/Selenium

PyPI:

https://pypi.ac.cn/project/selenium/

IRC/Slack:

Selenium聊天室

支持多个浏览器/驱动程序(Firefox、Chrome、Internet Explorer)以及远程协议。

支持的Python版本

  • Python 3.8+

安装

如果您系统上有

pip

,您可以直接安装或升级Python绑定

pip install -U selenium

或者,您可以从

PyPI

<https://pypi.ac.cn/project/selenium/#files>下载源代码包,解压缩后运行

python setup.py install

注意:您可能需要考虑使用

virtualenv

来创建隔离的Python环境。

驱动程序

Selenium需要一个驱动程序与所选浏览器交互。例如,Firefox需要

geckodriver

,在以下示例运行之前需要安装。确保它在您的

PATH

中,例如,将其放在

/usr/bin

/usr/local/bin

中。

如果未执行此步骤,将会出现错误

selenium.common.exceptions.WebDriverException: Message: 'geckodriver' executable needs to be in PATH.

其他支持的浏览器将有自己的驱动程序。以下是一些较受欢迎的浏览器驱动的链接。

Chrome:

https://chromedriver.chromium.org/downloads

Edge:

https://developer.microsoft.com/en-us/microsoft-edge/tools/webdriver/

Firefox:

https://github.com/mozilla/geckodriver/releases

Safari:

https://webkit.org/blog/6900/webdriver-support-in-safari-10/

示例 0

  • 打开一个新的Firefox浏览器

  • 在给定的URL加载页面

from selenium import webdriver

browser = webdriver.Firefox()
browser.get('https://selenium.net.cn/')

示例 1

  • 打开一个新的Firefox浏览器

  • 加载Yahoo主页

  • 搜索“seleniumhq”

  • 关闭浏览器

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

browser = webdriver.Firefox()

browser.get('http://www.yahoo.com')
assert 'Yahoo' in browser.title

elem = browser.find_element(By.NAME, 'p')  # Find the search box
elem.send_keys('seleniumhq' + Keys.RETURN)

browser.quit()

示例 2

Selenium WebDriver通常用作测试Web应用程序的基础。以下是一个使用Python标准库

unittest

的简单示例

import unittest
from selenium import webdriver

class GoogleTestCase(unittest.TestCase):

    def setUp(self):
        self.browser = webdriver.Firefox()
        self.addCleanup(self.browser.quit)

    def test_page_title(self):
        self.browser.get('http://www.google.com')
        self.assertIn('Google', self.browser.title)

if __name__ == '__main__':
    unittest.main(verbosity=2)

Selenium Grid(可选)

对于本地Selenium脚本,不需要Java服务器。

要使用远程Selenium,您还需要运行Selenium Grid。有关运行Selenium Grid的信息:https://selenium.net.cn/documentation/grid/getting_started/

要使用Remote WebDriver,请参阅:https://selenium.net.cn/documentation/webdriver/drivers/remote_webdriver/?tab=python

使用源代码!

在线查看源代码

官方

https://github.com/SeleniumHQ/selenium/tree/trunk/py

贡献

  • 为您的作品创建一个分支

  • 确保已安装

    tox

    (使用

    virtualenv

    是推荐的)

  • python3.8 -m venv .venv && . .venv/bin/activate && pip install tox

  • 在做出更改并提交之前,执行

    tox -e linting

  • 如果tox退出代码为

    0

    ,则提交并推送;否则,修复新引入的破坏。

  • flake8

    需要手动修复

  • “black”通常会自动重写断行,但文件未暂存,需要再次暂存。

  • “isort”通常会自动重写断行,但文件未暂存,需要再次暂存。

由以下支持