1

我有这段代码,如果元素存在,它将打印innerHTML值:

def display_hotel(self):
    for hotel in self.hotel_data:
        if hotel.find_element(By.CSS_SELECTOR, 'span[class="_a11e76d75 _6b0bd403c"]'):
            hotel_original_price = hotel.find_element(By.CSS_SELECTOR, 'span[class="_a11e76d75 _6b0bd403c"]')
            hotel_original_price = hotel_original_price.get_attribute('innerHTML').strip().replace(' ', '')

            print(f"Original:\t\t\t{hotel_original_price}")

当我继续并运行程序时,我收到一个错误

selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"css selector","selector":"span[class="_a11e76d75 _6b0bd403c"]"}

我希望如果元素不存在,它应该一起跳过,为什么即使在一个块span[class="_a11e76d75 _6b0bd403c"]下它仍然试图继续执行代码?if我在这里错过了什么吗?

4

1 回答 1

1

如果元素丢失,硒驱动程序会抛出异常。
为了使您的代码正常工作,您应该使用find_elements方法。
它返回与传递的定位器匹配的元素列表。
因此,如果有匹配项,则列表将包含 web 元素,而如果没有匹配项,它将返回一个空列表,而 python 将非空列表视为 BooleanTrue并且空列表是 Boolean False
所以你的代码可能如下:

def display_hotel(self):
    for hotel in self.hotel_data:
        if hotel.find_elements(By.CSS_SELECTOR, 'span[class="_a11e76d75 _6b0bd403c"]'):
            hotel_original_price = hotel.find_element(By.CSS_SELECTOR, 'span[class="_a11e76d75 _6b0bd403c"]')
            hotel_original_price = hotel_original_price.get_attribute('innerHTML').strip().replace(' ', '')

            print(f"Original:\t\t\t{hotel_original_price}")
于 2021-12-12T15:42:07.710 回答