WebDriver

WebDriver 是一个远程控制接口,可以对用户代理进行自省和控制。它提供了一种平台和语言中立的有线协议,作为进程外程序远程指示 Web 浏览器行为的一种方式。

¥WebDriver is a remote control interface that enables introspection and control of user agents. It provides a platform- and language-neutral wire protocol as a way for out-of-process programs to remotely instruct the behavior of web browsers.

能够编写可在不同平台上的许多浏览器中互换运行的指令集对于向用户提供一致的体验至关重要。随着 Web 平台的新一轮发展、设备多样性的增加以及技术之间真正互操作性的需求,WebDriver 为 跨浏览器测试 提供了工具。

¥To have the ability to write instruction sets that can be run interchangeably in many browsers on different platforms is critical to deliver a consistent experience to users. With the new wave of developments on the web platform, the increase diversity in devices and demands for real interoperability between the technologies, WebDriver provides tooling for cross-browser testing.

提供了一组接口,用于发现和操作 Web 文档中的 DOM 元素并控制用户代理的行为。它的主要目的是允许网络作者编写测试,使用户代理从单独的控制过程自动化,但也可以以允许浏览器内脚本控制(可能是单独的)浏览器的方式使用。

¥Provided is a set of interfaces to discover and manipulate DOM elements in web documents and to control the behavior of a user agent. It is primarily intended to allow web authors to write tests that automate a user agent from a separate controlling process, but may also be used in such a way as to allow in-browser scripts to control a — possibly separate — browser.

用法

¥Usage

那么 WebDriver 让你可以做什么以及它是什么样子的?由于 WebDriver 是编程语言中立的,因此这个问题的答案取决于你使用的 WebDriver 客户端以及语言的选择。

¥So what does WebDriver let you do and what does it look like? Since WebDriver is programming language neutral, the answer to this question depends on which WebDriver client you're using and the choice of language.

但是使用用 Python 编写的流行客户端,你与 WebDriver 的交互可能如下所示:

¥But using a popular client written in Python, your interaction with WebDriver might look like this:

python
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support.expected_conditions import presence_of_element_located



with webdriver.Firefox() as driver:

    driver.get("https://google.com/ncr")
    wait = WebDriverWait(driver, 10)
    driver.find_element(By.NAME, "q").send_keys("cheese" + Keys.RETURN)
    wait.until(presence_of_element_located((By.XPATH, '//*[@id="rcnt"]')))
    results = driver.find_elements(By.XPATH, "//a[@href]")

    for i, elem in enumerate(results):
        print(f'#{i} {elem.text} ({elem.get_attribute("href")})')

这可能会产生类似于以下的输出:

¥This might produce output akin to this:

#1 Cheese - Wikipedia (https://en.wikipedia.org/wiki/Cheese)

参考

¥Reference

命令

类型

能力

错误

规范

¥Specifications

也可以看看