0

I am new in this and I am trying to figure out if there is a better way. Scraping some data from similar pages, but elements are changing and my solution is:

try:
    p3 = driver.find_element_by_xpath("(//div/table)[2]/tbody/tr[contains(.,'4 - 10:00')]").text
except NoSuchElementException:
    try:
        p3 = driver.find_element_by_xpath("(//div/table)[2]/tbody/tr[contains(.,'3 - 00:00')]").text
    except NoSuchElementException:
        try:
            p3 = driver.find_element_by_xpath("(//div/table)[2]/tbody/tr[contains(.,'4 - 09:59')]").text
        except NoSuchElementException:
            try: 
                  ...
                        p3 = 0

and so on, but after some repetition:

SyntaxError: too many statically nested blocks

I found a way to handle this:

if p3 == 0:
           try:
               p3_2 = driver.find_element_by_xpath("(//div/table)[2]/tbody/tr[contains(.,'4 - 09:45')]").text
           except NoSuchElementException:
...

In this way I manage to do the job but I wonder if there is any better way?

1 Answers1

0

Save all your xpath-strings in a list, loop over this list until you have found a match. In the except you can just pass to attempt the next value.

for xpath in xpaths:
    try:
        p =  driver.find_element_by_xpath(xpath).text
    except NoSuchElementException:         
        pass
Olaf
  • 586
  • 5
  • 18