【问题标题】:retrying a code with minor changes until it works in python重试代码并进行细微更改,直到它在 python 中工作
【发布时间】:2020-03-26 11:53:53
【问题描述】:

如何使用try 函数重试代码? 想法是:

try:
interaction_type2 = driver.find_elements_by_xpath('web.page.interaction1')
except Error:
interaction_type2 = driver.find_elements_by_xpath('web.page.interaction2')

每次它应该添加到交互+1并循环它直到没有错误,所以尝试每次执行代码直到它成功。 我用循环尝试了它,但没有得到我想要的结果。

我目前的代码:

    while True:
    x = 'web.page.interaction-70"]'
    try:
        interaction_type2 = driver.find_elements_by_xpath(x) # next 136 then 202, 268
    except Exception:
        x = x.replace('70', '138')
        interaction_type2 = driver.find_elements_by_xpath(x)
    interaction_type2.click()

不知道如何在不写每一行的情况下更改每个错误。

【问题讨论】:

  • 循环是要使用的东西。给我们看看你写的循环?

标签: python-3.x loops try-catch


【解决方案1】:

您可以根据需要替换每个值。

for value in [70, 136, 202, 268]:
    x = f'web.page.interaction-{value}"]'
    try:
        interaction_type2 = driver.find_elements_by_xpath(x)
    except Exception:
        continue
    else:
        interaction_type2.click()
        break

如果您需要继续尝试超过 268 的值,请查看 itertools.count。你会遍历itertools.count(start=70, step=66)。但是,如果每个请求都失败,这可能会很危险,从而导致无限循环。您可能希望改为使用 range(70, some_high_value, 66) 来限制您的搜索。

【讨论】:

  • 谢谢,从逻辑角度来看,这应该可以解决我的问题,但是,我现在收到“列表”对象没有点击属性的错误消息(我正在使用 selenium)
  • 这真的应该作为一个单独的问题提出。但是,如果您确定有一个元素与此描述匹配,请从 find_elements_by_xpath 切换到 find_element_by_xpath。 (注意删除的“s”。)
  • 嗨@Ochitsuku,这回答了你的问题吗?如果是这样,如果您在它旁边标记绿色复选标记,我将不胜感激。它使其他人更容易找到解决此问题的可靠解决方案。
  • 我还是要玩它,@Arya McCarthy 到目前为止,它并没有解决我的问题,但我想我可以用你的信息解决它 :)
猜你喜欢
  • 1970-01-01
  • 2018-07-25
  • 1970-01-01
  • 2016-01-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多