NoSuchElementException (SyntaxError: too many statically nested blocks)

痴心易碎 提交于 2021-01-29 12:43:17

问题


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:


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


来源:https://stackoverflow.com/questions/56451572/nosuchelementexception-syntaxerror-too-many-statically-nested-blocks

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!