【问题标题】:NoSuchElementException (SyntaxError: too many statically nested blocks)NoSuchElementException(SyntaxError:静态嵌套块过多)
【发布时间】:2019-06-04 21:27:38
【问题描述】:

我是这方面的新手,我正在尝试找出是否有更好的方法。 从类似页面中抓取一些数据,但元素正在发生变化,我的解决方案是:

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

等等,但经过一些重复:

SyntaxError: too many statically nested blocks

我找到了解决方法:

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

通过这种方式我设法完成了这项工作,但我想知道是否有更好的方法?

【问题讨论】:

    标签: python selenium-webdriver nosuchelementexception


    【解决方案1】:

    将所有 xpath 字符串保存在一个列表中,循环遍历该列表,直到找到匹配项。在 except 中,您可以通过尝试下一个值。

    for xpath in xpaths:
        try:
            p =  driver.find_element_by_xpath(xpath).text
        except NoSuchElementException:         
            pass
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-06-23
      • 1970-01-01
      • 1970-01-01
      • 2011-09-11
      • 1970-01-01
      • 1970-01-01
      • 2012-04-19
      • 2013-05-11
      相关资源
      最近更新 更多