简体   繁体   English

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

[英]how do I do a try and except statement with this selenium error

I am not sure how to take this selenium/webdriver exception and create a try/except/else statement with the following exception line. 我不确定如何处理此selenium / webdriver异常,并使用以下异常行创建try / except / else语句。 The website im scraping sometimes may not contain the element im looking for but I would like to address that exception and move on. 网站即时消息抓取有时可能不包含我正在寻找的元素,但我想解决该异常并继续前进。

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

Ive tried some variations of that line in my except statement to no avail. 我已经在我的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

im hoping to be able to have a try/except/else statement that opens the browser, looks for that element, if it returns an exception that states the element is there then the variable i was looking to store it into will be this default number. 我希望能够有一个try / except / else语句来打开浏览器,查找该元素,如果它返回一个异常,指出该元素在那里,那么我想要将其存储到的变量将是该默认数字。 Then continue running the rest of the code. 然后继续运行其余代码。

You'll need that exception type in your namespace in order to catch it, so add to your imports: 您需要在名称空间中使用该异常类型才能捕获它,因此将其添加到导入中:

from selenium.common.exceptions import WebDriverException

And then try changing your except statement to: 然后尝试将您的except语句更改为:

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

That way you're only catching the specific exceptions you want to bypass, and raising anything else. 这样,您仅捕获要绕过的特定异常,并引发其他任何异常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM