I have a python code to obtain all the elements with
try:
restaurantsReviews = self.driver.find_elements(By.XPATH, '//div[@class="review-container"]')
except:
#los hoteles tienen las opiniones en otro elemento
restaurantsReviews = self.driver.find_elements(By.XPATH, '//div[@class="YibKl MC R2 Gi z Z BB pBbQr"]')
The element "review-container" does not exists but there is no exception. If I use find_element()
instead it raise the exception, but I need to use find_elements()
because is a recurrent element.
find_elements() find elements given a By
strategy and locator. It returns a list of WebElements.
find_elements()
is defined as:
def find_elements(self, by=By.ID, value: Optional[str] = None) -> List[WebElement]:
"""Find elements given a By strategy and locator.
:Usage:
::
elements = driver.find_elements(By.CLASS_NAME, 'foo')
:rtype: list of WebElement
"""
if isinstance(by, RelativeBy):
_pkg = ".".join(__name__.split(".")[:-1])
raw_function = pkgutil.get_data(_pkg, "findElements.js").decode("utf8")
find_element_js = f"/* findElements */return ({raw_function}).apply(null, arguments);"
return self.execute_script(find_element_js, by.to_dict())
if by == By.ID:
by = By.CSS_SELECTOR
value = f'[id="{value}"]'
elif by == By.CLASS_NAME:
by = By.CSS_SELECTOR
value = f".{value}"
elif by == By.NAME:
by = By.CSS_SELECTOR
value = f'[name="{value}"]'
# Return empty list if driver returns null
# See https://github.com/SeleniumHQ/selenium/issues/4555
return self.execute(Command.FIND_ELEMENTS, {"using": by, "value": value})["value"] or []
So incase no WebElemens are found it returns an empty list . Hence find_elements()
doesn't raises any exception.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.