我如何尝试此硒错误的try和except语句

时间:2019-06-06 18:48:46

标签: python selenium web-scraping pycharm

我不确定如何处理此selenium / webdriver异常,并使用以下异常行创建try / except / else语句。网站即时消息抓取有时可能不包含我正在寻找的元素,但我想解决该异常并继续前进。

selenium.common.exceptions.WebDriverException:消息:无法访问chrome

我在我的except语句中尝试了该行的一些变体,但无济于事。

def planCosts():
    driver.get("https://shop.freedommobile.ca/devices/Samsung/Galaxy_S10+?sku=887276301570&planSku=Freedom%20250MB")

    MSRP = wait.until(EC.presence_of_all_elements_located((By.CSS_SELECTOR, '.cKlhCz')))
    MSRP = MSRP[0].text
    MSRP = re.findall(r'\d+', MSRP)
    MSRP = int(MSRP[0])
    print(MSRP)

    # grabbing the lowest upfront payment from string of min and max
    try: # checks to see if element exist
        upfrontPaymentRaw = wait.until(EC.presence_of_all_elements_located((By.CSS_SELECTOR, '.col-lg-6 .fTfebt')))

        upfrontPayment = upfrontPaymentRaw[0].text

    except selenium.common.exceptions.WebDriverException: #if I get an error looking for it then just make it default number above(MSRP)
        myTabCharge = MSRP

    else: #if no error run this code
        upfrontPayment = re.findall(r'\d+', upfrontPayment)
        upfrontPaymentLowest = int(upfrontPayment[0])
        upfrontPaymentHighest = int(upfrontPayment[1])

        myTabCharge = (upfrontPaymentHighest - upfrontPaymentLowest) / 24
我希望能够有一个try / except / else语句来打开浏览器,寻找该元素,如果它返回一个异常,指出该元素存在,那么我想要存储的变量将是此默认号码。然后继续运行其余代码。

1 个答案:

答案 0 :(得分:1)

您需要在名称空间中使用该异常类型才能捕获它,因此将其添加到导入中:

from selenium.common.exceptions import WebDriverException

然后尝试将您的except语句更改为:

except WebDriverException as e:
    if e.msg.strip().endswith("chrome not reachable"):
        myTabCharge = MSRP
    else:
        raise

这样,您仅捕获要绕过的特定异常,并引发其他任何异常。