尝试使用硒在网站中查找元素,但如果其他条件不起作用

时间:2019-03-15 12:25:21

标签: python-3.x selenium selenium-webdriver

我正在尝试查找网站中的某些元素,如果发现我必须打印 check_1 check_2 ,否则,请打印 。但是我被困在if else条件下,因为if-else条件不起作用。 我的代码:

try:
    if driver.find_element_by_css_selector('div.hero__media'):
        sheet.cell(row=i, column=4).value = 'grid'
        print('grid')

    elif driver.find_elements_by_css_selector('div.flexigrid--no-sublinks.flexigrid--4-2up'):
        sheet.cell(row=i, column=4).value = 'banner'
        print('banner')
    else:
        raise Exception('This is the exception you expect to handle')
except Exception as error:
    sheet.cell(row=i, column=4).value = 'none'
    print('none')

最后,它抛出了手动异常,因此,如果我找不到该元素,它将进入除。 编辑1:我尝试将条件从if更改为if if now,第二条件再次不起作用,if else出了点问题。 Edit1_Code:

    if driver.find_element_by_css_selector('div.flexigrid--no-sublinks.flexigrid--4-2up'):
        sheet.cell(row=i, column=4).value = 'grid'
        print('grid')
    elif driver.find_elements_by_css_selector('div.hero__media'):
        sheet.cell(row=i, column=4).value = 'banner'
        print('banner')
    else:
        raise Exception('This is the exception you expect to handle')
except Exception as error:
    sheet.cell(row=i, column=4).value = 'none'
    print('none')```

2 个答案:

答案 0 :(得分:0)

尝试长度计数并检查是否有效。

if len(driver.find_elements_by_css_selector('div.hero__media'))>0:
            sheet.cell(row=i, column=4).value = 'grid'
            print('grid')

        elif len(driver.find_elements_by_css_selector('div.flexigrid--no-sublinks.flexigrid--4-2up'))>0:
            sheet.cell(row=i, column=4).value = 'banner'
            print('banner')
        else:
            raise Exception('This is the exception you expect to handle')


    except Exception as error:
        sheet.cell(row=i, column=4).value = 'none'
        print('none')```
last else is throwing manual exception so if I can't find the element it will go to except.

答案 1 :(得分:0)

您可以使用find_elements,获取大小并检查其是否不为0:

value = 'none'
if len(driver.find_elements_by_css_selector('div.hero__media')) > 0:
    value = 'grid'

elif len(driver.find_elements_by_css_selector('div.flexigrid--no-sublinks.flexigrid--4-2up')) > 0:
    value = 'banner'

print(value)
sheet.cell(row=i, column=4).value = value

您的代码中的问题是,如果第一个元素不存在,则Selenium抛出NoSuchElementException并跳过其他代码。陷入except部分,永远不要去elif

您还可以检查https://www.geeksforgeeks.org/given-two-strings-find-first-string-subsequence-second/be如何检查元素是否存在。