【发布时间】:2022-01-16 08:15:03
【问题描述】:
我有这段代码,如果元素存在,它将打印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 块下它仍然试图继续执行代码?我在这里有什么遗漏吗?
【问题讨论】:
-
只需使用 try 和 except 来捕获错误。
-
你会在 except 块中编写什么代码?写
pass可以吗? -
可以这样做或继续。
标签: python-3.x selenium selenium-webdriver findelement