简体   繁体   English

Selenium - 检查元素是否存在,否则检查是否存在另一个元素(在python中)

[英]Selenium - check if element is present else check if another element is present (in python)

I'm writing a program that scrapes courses from my schools website and i'm trying to check what element is present after I click on the search button. 我正在编写一个程序,从我的学校网站上删除课程,我试图检查点击搜索按钮后出现的元素。

If 'id1' is present then that means the course is not available and the next course needs to be searched, else if 'id2' is present then that means the course is available so scrape it and search the next course. 如果'id1'存在则表示该课程不可用且需要搜索下一个课程,否则如果'id2'存在则表示该课程可用,因此抓取它并搜索下一个课程。

This is what I have at the moment but it's not working. 这就是我现在所拥有的,但它不起作用。 I've tired using webdriverwait with conditional statements but I couldn't get it to work either. 我已经厌倦了使用带有条件语句的webdriverwait,但我也无法让它工作。 So how can I solve this? 那我怎么解决这个问题呢?

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(): scrapeAndModifySearch():

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

getCourses(): 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

Seems you've mixed up your locators. 好像你搞定了你的定位器。 That last line should be: 最后一行应该是:

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

'id2' is not valid xpath (at least not for a HTML doc). 'id2'无效xpath(至少不适用于HTML文档)。

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

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