因此,我正在尝试进行自动登录到我的帐户。这是我的代码rn:
import selenium.webdriver as webdriver
def get_all_results(Username, password):
url = "https://portail.sainteanne.ca/pluriportail/fr/MainExterne.srf?P=LoginReq"
browser = webdriver.Chrome()
browser.get(url)
Username_sbox = browser.find_element_by_id("NomLogin")
Username_sbox.send_keys(Username)
Username_sbox.submit()
Pass_sbox = browser.find_element_by_id("MotPasse")
Pass_sbox.send_keys(password)
Pass_sbox.submit()
browser.close()
get_all_results("random_username123232", "random_password1234")
这就是我得到的结果:
Traceback (most recent call last):
File "c:\Users\CSA\OneDrive - College Sainte-Anne\Programming\PYTHON\Learning\WS\tempCodeRunnerFile.py", line 18, in <module>
get_all_results("random_username123232", "random_password1234")
File "c:\Users\CSA\OneDrive - College Sainte-Anne\Programming\PYTHON\Learning\WS\tempCodeRunnerFile.py", line 8, in get_all_results
Username_sbox = browser.find_element_by_id("NomLogin")
File "C:\Users\CSA\AppData\Local\Programs\Python\Python38-32\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 360, in find_element_by_id
return self.find_element(by=By.ID, value=id_)
File "C:\Users\CSA\AppData\Local\Programs\Python\Python38-32\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 976, in find_element
return self.execute(Command.FIND_ELEMENT, {
File "C:\Users\CSA\AppData\Local\Programs\Python\Python38-32\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 321, in execute
self.error_handler.check_response(response)
File "C:\Users\CSA\AppData\Local\Programs\Python\Python38-32\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 242, in check_response
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.NoSuchElementException: **Message: no such element: Unable to locate element: {"method":"css selector","selector":"[id="NomLogin"]"}
(Session info: chrome=79.0.3945.130)**
我刚刚开始使用浏览器实现自动化,我感到困惑。请帮助。谢谢 :)。
答案 0 :(得分:0)
您将需要在代码中放置等待以帮助查找元素。有时,在页面完成加载元素之前会先查找元素,这将导致“找不到元素”错误。将此添加到您的代码中:
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
Username_sbox = WebDriverWait(browser, 10).until(
EC.presence_of_element_located((By.ID, "NomLogin"))
Pass_sbox = WebDriverWait(browser, 10).until(
EC.presence_of_element_located((By.ID, "MotPasse"))
这将使浏览器有时间加载,然后抛出找不到元素的错误。
有关等待的更多信息,请参见:https://selenium-python.readthedocs.io/waits.html
答案 1 :(得分:0)
我终于找到了让selenium运行任何功能之前让浏览器加载的方法:
import selenium.webdriver as webdriver
url = "url.of.the.website.com"
browser = webdriver.Chrome()
browser.get(url)
browser.implicitly_wait(10) # <--- THIS IS THE FUNCTION I WAS LOOKING FOR
#...Enter username.... blablabla and DONE!