在前端,id是唯一的,只屬於一個元素。
在python中,元素定位的方法如下:
def find_element_by_id(self, id_): """Finds an element by id. :Args: - id\_ - The id of the element to be found. :Returns: - WebElement - the element if it was found :Raises: - NoSuchElementException - if the element wasn't found :Usage: element = driver.find_element_by_id('foo') """ return self.find_element(by=By.ID, value=id_)
我們可以看到,通過find_element_by_id()方法,傳入id即可定位到元素。
參數id:元素的id屬性。
返回值:如果定位到了元素,返回WebElement對象。否則拋出NoSuchElementException異常
用法舉例:element = driver.find_element_by_id("foo")
該方法最終調用的是find_element(by=By.ID, value=id_),並返回WebElement對象。
拓展:selenium中,八種定位方式最終都是通過調用find_element(by, value)方法
問題:在前端,如果id是動態變化時該怎么辦?