简体   繁体   中英

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.

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

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

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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