【问题标题】:Selenium - check if element is present else check if another element is present (in python)Selenium - 检查元素是否存在否则检查另一个元素是否存在(在python中)
【发布时间】:2017-04-03 02:35:05
【问题描述】:

我正在编写一个从我的学校网站上抓取课程的程序,并且我正在尝试在单击搜索按钮后检查存在哪些元素。

如果存在“id1”,则表示该课程不可用,需要搜索下一个课程,否则如果存在“id2”,则表示该课程可用,因此抓取它并搜索下一个课程。

这是我目前拥有的,但它不起作用。我已经厌倦了使用带有条件语句的 webdriverwait,但我也无法让它工作。那么我该如何解决呢?

while(i < len(courseNumList)):
   self.clearAndSearch(courseNumList[i], coursePrefixList[i])

   if(len(self.driver.find_elements_by_id('id1')) > 0):
      i = i + 1
      continue
   self.scrapeAndModifySearch(courses, INDEX_NAME, TYPE_NAME)
      i = i + 1

scrapeAndModifySearch():

def scrapeAndModifySearch(self, courses, esindex, estypename):
   self.getCourses(courses, esindex, estypename)
   self.modifySearch()

getCourses():

def getCourses(self, courses, INDEX_N, TYPE_N):
   course = {}

   try:
      element_present = EC.presence_of_element_located((By.ID, 'id2'))
      WebDriverWait(self.driver, 30).until(element_present)
   except TimeoutException:
      print ("Loading took too much time!")

   classSectionsFound = self.driver.find_element_by_xpath('id2').text

【问题讨论】:

  • 该元素可能存在只是还不可见,你试过'self.driver.find_element_by_id('id1').is_Displayed()'吗?
  • 您需要提供有关它不起作用的更多详细信息。发生什么了?如果遇到异常,则需要添加堆栈跟踪。
  • 我得到的错误是:selenium.common.exceptions.NoSuchElementException: Message: {"errorMessage":"Unable to find element with xpath 'id2'
  • 我认为发生的事情是,当我在网页上单击搜索时,未找到元素 id2,因为单击时未执行搜索。我刚刚尝试使用 is_Displayed() 但同样的事情正在发生。
  • 您提供的代码不会产生此错误。请添加相关代码。

标签: python selenium selenium-webdriver element


【解决方案1】:

您似乎混淆了定位器。最后一行应该是:

   classSectionsFound = self.driver.find_element_by_id('id2').text

'id2' 不是有效的 xpath(至少对于 HTML 文档来说不是)。

【讨论】:

    猜你喜欢
    • 2018-01-23
    • 2021-05-17
    • 1970-01-01
    • 2021-07-08
    • 2012-03-22
    • 2012-11-20
    相关资源
    最近更新 更多