【问题标题】:how do I do a try and except statement with this selenium error如何使用此硒错误执行 try 和 except 语句
【发布时间】:2019-10-22 07:39:02
【问题描述】:

我不确定如何处理这个 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 语句来打开浏览器,查找该元素,如果它返回一个异常说明该元素存在,那么我希望将它存储到的变量将是这个默认号码。然后继续运行其余代码。

【问题讨论】:

    标签: python selenium web-scraping pycharm


    【解决方案1】:

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

    from selenium.common.exceptions import WebDriverException

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

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

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

    【讨论】:

    • 您好 Silver,感谢您的帮助。我已经实施了你的建议。不幸的是,我现在收到一个错误:NameError: name 'WebDriverException' is not defined
    • 啊,没问题。 Python 需要命名空间中的类型才能对其进行检查。查看我的编辑
    • 也许还有一个障碍? AttributeError:“WebDriverException”对象没有属性“消息”
    • 嗯,这可能是我们之间的 Python 版本差异?改用msg
    猜你喜欢
    • 1970-01-01
    • 2011-09-29
    • 1970-01-01
    • 1970-01-01
    • 2021-08-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多