Home > Back-end >  Can't locate an href element with selenium python
Can't locate an href element with selenium python

Time:10-05

So this is the element i want to click:

<a href="javascript:void(0);" class="logged_time" id="logged_2021-09-01" presence_id="q25474p2842324" user="haha" date="2021-09-01" worked="8:00" user_ad="hahaha" token="irrelevant" action="log">0:00</a>

Can't use the href since it's the same with many other elements, what I want is to click it by it's id but my code doesn't work: this is my code:

browser.find_element_by_xpath('//*[@id="logged_2021-09-01"]').click()

An this is the error:

Message: no such element: Unable to locate element: {"method":"xpath","selector":"//*[@id="logged_2021-09-01"]"}

Update: enter image description here

CodePudding user response:

Try using the following code. It will try to find the <a> tag specifically and search the id starting with "logged_". The id will probably change each day you log in, so not hardcoding the date might save you some time in the future. Also use a WebDriverWait to avoid searching for the element before the page has been loaded. Else the element will not be found, since the page/element hasn't loaded yet.

try: 
    xpath = '//a[contains(@id, "logged_")]'
    WebDriverWait(driver, 5).until(EC.presence_of_element_located((By.XPATH, xpath)))
              
    element = browser.find_element_by_xpath(xpath)

    element.click()

except:
    # Ideally you catch each error separately; TimeoutException, NoSuchElementException, ...
    pass

CodePudding user response:

Actually my code works the thing is that I was trying it with the idle console and I thought that once you open the browser calling browser = webdriver.Chrome() then you can navigate manually everywhere keeping the browser object viable to use.

  • Related