如果找不到元素,则检查元素无异常

时间:2018-03-11 05:12:17

标签: python selenium python-3.6

我正在尝试探测页面是否存在特定元素,因为它会改变我的进程中的条件。我使用.find_element_by_xpath来查找元素并且它可以正常工作,但如果在没有元素的页面上执行搜索,则会出现异常并且进程停止。

我是selenium的新手并查看了文档,但我无法找到我正在寻找的内容。

感谢任何指导。

我的经纪人:

try:
    browser.find_element_by_xpath('//*[@id="message"]')
except NoSuchElementException as e:
    print('No Such Element has occurred')
    pass

这里有追踪:

Traceback (most recent call last):
  File "C:\Program Files\JetBrains\PyCharm Community Edition 2017.3.3\helpers\pydev\pydev_run_in_console.py", line 53, in run_file
    pydev_imports.execfile(file, globals, locals)  # execute the script
  File "C:\Program Files\JetBrains\PyCharm Community Edition 2017.3.3\helpers\pydev\_pydev_imps\_pydev_execfile.py", line 18, in execfile
    exec(compile(contents+"\n", file, 'exec'), glob, loc)
  File "C:/Users/DWL/Desktop/comment_bot/comment_bot.py", line 187, in <module>
    advertise()
  File "C:/Users/DWL/Desktop/comment_bot/comment_bot.py", line 102, in advertise
    advert = [popper(adv_vc, add_vc, ad_comment) for x in range(len(adv_vc))]
  File "C:/Users/DWL/Desktop/comment_bot/comment_bot.py", line 102, in <listcomp>
    advert = [popper(adv_vc, add_vc, ad_comment) for x in range(len(adv_vc))]
  File "C:/Users/DWL/Desktop/comment_bot/comment_bot.py", line 120, in popper
    post_comment(a[0][0])
  File "C:/Users/DWL/Desktop/comment_bot/comment_bot.py", line 158, in post_comment
    browser.find_element_by_xpath('//*[@class="style-scope ytd-message-renderer"]')
  File "C:\Python\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 385, in find_element_by_xpath
    return self.find_element(by=By.XPATH, value=xpath)
  File "C:\Python\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 955, in find_element
    'value': value})['value']
  File "C:\Python\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 312, in execute
    self.error_handler.check_response(response)
  File "C:\Python\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 242, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//*[@class="style-scope ytd-message-renderer"]"}
  (Session info: chrome=64.0.3282.186)
  (Driver info: chromedriver=2.35.528161 (5b82f2d2aae0ca24b877009200ced9065a772e73),platform=Windows NT 10.0.16299 x86_64)

2 个答案:

答案 0 :(得分:1)

您可以使用try-except块来忽略这样的异常:

from selenium.common.exceptions import NoSuchElementException

try:
    driver.find_element_by_xpath(...)
except NoSuchElementException:
    print("Element not found")

答案 1 :(得分:1)

根据堆栈跟踪,抛出错误的行是您要查找的xpath //*[@class="style-scope ytd-message-renderer"],而不是try except块中的代码。

另一种方法是使用find_elements并检查大小是否为0

elements = browser.find_elements_by_xpath('//*[@class="style-scope ytd-message-renderer"]')
if (len(elements) > 0):
    # do something