WebDriver 中的 find_element() 方法用来查找元素,并返回 WebElement 对象。是 WebDriver 中最常用的方法。

前面提到的八种定位方式都有对应的方法,如find_element_by_id()

在 WebDriver 中还有一种用法,就是单纯的find_element()。需要通过参数传入定位方式和定位语句。

from selenium.webdriver.common.by import By

driver.find_element(By.ID, "kw")
driver.find_elements(By.TAG_NAME, "input")

这种方法要借助 By 来传入定位方式,需要先引入,主要是为了防止定位方式写错。

使用find_element()的好处是方法名不会写死,定位方式可以通过参数传递,在一些框架中使用时会更加灵活一些。

以下是定位方式与 By 中的属性对应清单:

定位方式

By

id

By.ID

name

By.NAME

class_name

By.CLASS_NAME

tag_name

By.TAG_NAME

link_text

By.LINK_TEXT

partial_link_text

By.PARTIAL_LINK_TEXT

css_selector

By.CSS_SELECTOR

xpath

By.XPATH

find_element 与 find_elements

每种 find_element()方法,包括find_element_by_id()在查找元素时,如果定位语句不唯一,能够查到多个函数的话,默认值返回页面中出现的第一个。也就是说定位不唯一,那得到的元素可能就不是你想要的。

以下是返回的元素对象结果:

<selenium.webdriver.remote.webelement.WebElement (session="8b1282534fe7b0f87743984601b27047", element="2a08389e-3c5f-4c14-be8d-1046f4a53b76")>

通过 find_elements() 或者find_elements_by_id() (注意都多了个 s),将以列表的形式返回所有符合条件的元素。