【问题标题】:Python selenium: use while true/false to continue running script when element not presentPython selenium:当元素不存在时使用 while true/false 继续运行脚本
【发布时间】:2021-03-11 20:26:42
【问题描述】:

如果不满足某个条件,我编写了一个 selenium 脚本以继续运行。如:

condition = driver.find_element_by_css_selector('div.S_txt1').is_displayed()
while not condition:
   run this 

如果我运行代码,我会收到此消息:

Message: no such element: Unable to locate element: {"method":"css selector","selector":"div.S_txt1"}

我找到了解决方法:

condition = []
while condition == []:
   condition = driver.find_elements_by_css_selector('div.S_txt1')
   run this

这样,如果没有找到该元素,那么列表仍然是空的,代码将继续运行。

但我仍然想知道如何以 True / False 方式进行操作。无论如何,这可以实现吗?

【问题讨论】:

    标签: python selenium selenium-webdriver web-scraping


    【解决方案1】:

    你试过了吗

    if driver.find_element_by_css_selector('div.S_txt1').is_displayed():
        run this
    else:
        run that
    

    【讨论】:

      【解决方案2】:

      如果大于0,检查元素的长度

      if len(driver.find_elements_by_css_selector('div.S_txt1'))>0 :
         print("elements found")
         //your statement
      else:
         print("No such element")
         //your statement
      

      或者尝试..except 块

      try:
         driver.find_element_by_css_selector('div.S_txt1')
         print("element found")
         //your statement
      except:
         pass
         print("No such element")
         //your statement
      

      【讨论】:

        【解决方案3】:

        正如其他人所说,您可以检查返回元素的大小:

        while condition == driver.find_elements_by_css_selector('div.S_txt1') > 0:
            run this
        

        您还可以使用 ExpectedConditions: https://selenium-python.readthedocs.io/waits.html#explicit-waits

        presence_of_element_located

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2022-01-20
          • 1970-01-01
          • 2021-09-27
          • 2022-01-16
          • 2021-01-24
          • 1970-01-01
          • 2017-10-31
          相关资源
          最近更新 更多