【问题标题】:Element sometimes appears and sometimes does not, how to continue script either way?元素有时出现有时不出现,如何继续脚本?
【发布时间】:2020-01-31 21:12:32
【问题描述】:

我的 selenium (python) 脚本正在作为仪表板的网站上做一些工作,即当我与此仪表板上的元素交互时,实际的网页/链接不会改变。我提到这一点是因为我认为只是通过 driver.get() 命令在不同的链接上跳跃以避免我现在遇到的一些问题。

在某一时刻,脚本到达仪表板的一部分,由于某种原因,在我的 一些 测试运行期间有一个元素,而其他时候该元素不存在。我有几行与这个元素交互,因为它是我想要.click() 的另一个元素的方式。因此,当此元素不存在时,我的脚本将停止工作。这是一个脚本,它会在开始时重复相同的动作,但会有小的变化,所以我需要以某种方式集成某种我猜的“if”命令。

我的目标是写一些这样的东西: - 如果此元素不存在,则跳过与其交互的代码行并跳转到下一行。如果该元素明显存在,则继续。

day = driver.find_element_by_xpath('/html/body/div[4]/table/tbody/tr[4]/td[2]/a')
ActionChains(driver).move_to_element(day).click().perform()

driver.implicitly_wait(30)

lizard2 = driver.find_element_by_xpath('/html/body/div[5]/div/div[2]/div[1]/img')
ActionChains(driver).move_to_element(lizard2).perform()
x2 = driver.find_element_by_xpath('/html/body/div[5]/div/div[2]/div[2]')
ActionChains(driver).move_to_element(x2).click().perform()

driver.execute_script('window.scrollTo(0, document.body.scrollHeight)')

因此,以“lizard2”开头并进入 ActionChains 行的块是与此元素交互的块,有时在脚本来回执行任务时不明显,有时不明显。

前两行只是让我进入具有此随机出现元素的仪表板阶段的代码。最后的滚动命令如下。如前所述,如果找不到此 'lizard2' 和 'x2' 元素,我需要忽略中间部分并继续滚动部分。

如果这令人困惑且不够简洁,我深表歉意,我很高兴听到你们的想法并提供任何其他信息/细节,谢谢!

【问题讨论】:

  • 我想我的问题是 - 我可以在脚本的特定部分制作一个“平行”(不确定使用什么词)脚本来寻找这个元素,并激活 if元素出现了吗?
  • 一个(hacky)解决方案是将其包装在try 和相应的except 语句中
  • 我感觉你只需要使用一个WebDriverWait...但是如果这个项目真的是随机的,你可以使用一个监听器:selenium.dev/selenium/docs/api/java/org/openqa/selenium/support/…

标签: python html selenium if-statement element


【解决方案1】:

您可以像这样在try/except 块内简单地执行您的find_element_by_xpath

from selenium.common.exceptions import NoSuchElementException
try:
    myElement = driver.find_element_by_xpath(...)
    #Element exists, do X
except NoSuchElementException:
    #Element doesn't exist, do Y

编辑:就像在您的问题中添加 cmets 中的某个人建议这种方法是“hacky”,它实际上非常 Pythonic 并且非常标准。

【讨论】:

【解决方案2】:
private boolean isElementPresent(By by) {
try {
    driver.findElement(by);
    return true;
} catch (NoSuchElementException e) {
    return false;
}

}

【讨论】:

    【解决方案3】:

    @Lucan 回答:

    您可以像这样在 try/except 块中简单地执行 find_element_by_xpath:

    from selenium.common.exceptions import NoSuchElementException
    try:
        myElement = driver.find_element_by_xpath(...)
        #Element exists, do X
    except NoSuchElementException:
        #Element doesn't exist, do Y
    

    【讨论】:

      猜你喜欢
      • 2014-08-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-18
      • 1970-01-01
      • 1970-01-01
      • 2019-01-11
      相关资源
      最近更新 更多