0

I am trying to find an element in the DOM/HTML using css selector with selenium and python.

However I am receiving an error, the syntax appears to be the same but it outputs an error.

Here is the code:

def find_element(self):
        var1, var2 = input("enter class and div (seperated by comma): ").split(',')
        var_list = [var1,var2]
        for x in var_list:
            x.strip()
        find_elem = ("{}[class*='{}']").format(var1, var2)
        try:
            if (self.driver.find_element_by_css_selector("{}[class*='{}']".format(var1,var2)).is_displayed()):
                print('Exist')
            else:
                print('does not exist')
        except Exception as e:
            raise Exception('Not looking for element')

Here is the error:

Traceback (most recent call last):
  File "/home/gregory/projects/parser/Scraper1/WebGrab.py", line 55, in find_element
    if (self.driver.find_element_by_css_selector("{}[class*='{}']".format(var1,var2)).is_displayed()):
  File "/home/gregory/.local/lib/python3.6/site-packages/selenium/webdriver/remote/webdriver.py", line 598, in find_element_by_css_selector
    return self.find_element(by=By.CSS_SELECTOR, value=css_selector)
  File "/home/gregory/.local/lib/python3.6/site-packages/selenium/webdriver/remote/webdriver.py", line 978, in find_element
    'value': value})['value']
  File "/home/gregory/.local/lib/python3.6/site-packages/selenium/webdriver/remote/webdriver.py", line 321, in execute
    self.error_handler.check_response(response)
  File "/home/gregory/.local/lib/python3.6/site-packages/selenium/webdriver/remote/errorhandler.py", line 242, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.NoSuchElementException: Message: Unable to locate element: div[class*='lga']

I am using google.com landing page as the test case: The element I am looking for is the Google logo. This is the element I have from the inspector. I input "div" and "lga" as div,lga.

BONUS if you can tell me why the strip function is not working either.

Thanks!

Community
  • 1
  • 1

1 Answers1

1

x.strip() doesn't change x, so you'd need something like x = x.strip().. but that won't work in the loop you have, because changing x still won't change var1, var2.

So, instead, just do something along the lines of:

find_elem = ('{}[class*="{}"]').format(var1.strip(), var2.strip())

Quick look at the google homepage, I don't see any divs with class similar to lga, though there is a div with id=lga. So my guess as to why it can't be found is, because it's not there.

pbuck
  • 4,291
  • 2
  • 24
  • 36