0

I have a Selenium script, where I enter a series of websites, and get some data. Sometimes the data does not exist, and I simply want to write something like "Cant find x data" onto my string. The current script does this:

#Getting "Status"
try:
    strValue = strValue + ',' + browser.find_element_by_css_selector('#visKTTabset > div.h-tab-content > div.h-tab-content-inner > div:nth-child(12) > table > tbody > tr.stripes-even > td:nth-child(3) > span').text
except webdriver.NoSuchElementException:
    StrValue = strValue + ',' + "Status not found"

The script works when the "Status" actually exists, but id does not get into the "except" part. The top of my script has this:

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.common.exceptions import NoSuchElementException

browser = webdriver.Chrome(executable_path=r'C:\Selenium\chromedriver.exe')
browser.get('https://motorregister.skat.dk/dmr-front/dmr.portal?_nfpb=true&_nfpb=true&_pageLabel=vis_koeretoej_side&_nfls=false')
browser.implicitly_wait(10)  # Will set the global wait to 10 seconds.gnash

I tried the solution here: Try except in python/selenium still throwing NoSuchElementException error but it didnt work.

  • Do you define `strValue` before the `try/except` ? – andreihondrari Apr 23 '19 at 08:09
  • It returns an exit code so it doesn’t qualify for the exception – x3l51 Apr 23 '19 at 08:14
  • @anonjnr I get this error: selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"css selector","selector":"#visKTTabset > div.h-tab-content > div.h-tab-content-inner > div:nth-child(12) > table > tbody > tr.stripes-even > td:nth-child(4) > span"} – Ercan Ciftci Apr 23 '19 at 08:20
  • @andreihondrari I do :) – Ercan Ciftci Apr 23 '19 at 08:21
  • See answer below. Also you could do something like strValue = 0 and use an if Statement instead of the try block? – x3l51 Apr 23 '19 at 08:26

2 Answers2

1

Python names are case sensitive, so perhaps you need:

strValue = strValue + ',' + "Status not found"
brunns
  • 2,689
  • 1
  • 13
  • 24
0

NoSuchElementException is not part of webdriver, it's part of selenium.common.exceptions

try:
    strValue = strValue + ',' + browser.find_element_by_css_selector('#visKTTabset > div.h-tab-content > div.h-tab-content-inner > div:nth-child(12) > table > tbody > tr.stripes-even > td:nth-child(3) > span').text
except NoSuchElementException:  # without webdriver.
    StrValue = strValue + ',' + "Status not found"

And make sure strValue is declared before the try except block.

As a side note, in Python strValue should be str_value

Guy
  • 46,488
  • 10
  • 44
  • 88
  • 2
    Thank you so much. I've been stuck with this, for far too long, your solution - along with Brunns answer helped out – Ercan Ciftci Apr 23 '19 at 08:29