Python使用Selenium实现邮箱登录时遭遇NoSuchElementException错误
Let's walk through the problems in your code and fix them one by one:
1. Invalid CSS Selectors (The Root Cause of the NoSuchElementException)
The error you're seeing happens because your CSS selectors like "email" and "submit" don't match any actual elements on the Microsoft login page—those aren't valid identifiers for the fields and buttons you're trying to target.
For the Live login page, the key elements have specific, reliable IDs you can use instead:
- The email input field has an ID of
i0116 - The password input field has an ID of
i0118 - Both the "Next" and "Sign in" buttons share the ID
idSIButton9
You can use find_element_by_id() for simpler, more stable targeting (or if you prefer CSS, use #i0116 which targets elements with the ID i0116).
2. File Reading Bug
When you use readlines(), each line from the file includes a trailing newline character (\n). If you pass info[0] and info[1] directly to your bot function, your email and password will have extra whitespace that will cause login failures. You need to strip these characters with strip().
Updated Working Code
Here's the revised version of your script with all fixes applied, plus some extra stability improvements:
from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC def bot(usr, pas): br = webdriver.Chrome() br.get("https://login.live.com/") # Wait for email field to load (prevents race conditions) user = WebDriverWait(br, 10).until( EC.presence_of_element_located((By.ID, "i0116")) ) user.clear() user.send_keys(usr) # Click "Next" button next_btn = WebDriverWait(br, 10).until( EC.element_to_be_clickable((By.ID, "idSIButton9")) ) next_btn.click() # Wait for password field to load after clicking next passwd = WebDriverWait(br, 10).until( EC.presence_of_element_located((By.ID, "i0118")) ) passwd.clear() passwd.send_keys(pas) # Click "Sign in" button sign_in_btn = WebDriverWait(br, 10).until( EC.element_to_be_clickable((By.ID, "idSIButton9")) ) sign_in_btn.click() if __name__ == "__main__": with open("Details.txt", "r") as file: # Read lines and strip whitespace/newlines info = [line.strip() for line in file.readlines()] # Assuming Details.txt has email on first line, password on second bot(info[0], info[1])
Extra Improvements Added:
- Used
WebDriverWaitwith explicit waits instead of relying on implicit timing. This ensures elements are fully loaded before interacting with them, which prevents more "no such element" errors. - Used a
withstatement for file handling, which automatically closes the file for you (cleaner and safer than manualclose()calls).
内容的提问来源于stack exchange,提问作者Alex

