简体   繁体   中英

Can't locate an href element with selenium python

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

Update 2: My code works, the thing is that I was trying to run it with the IDLE console. I thought that once you have opened the browser by calling browser = webdriver.Chrome() , then you can navigate everywhere manually while keeping the browser object viable for use.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM