我正在尝试自动登录网站,下面是我使用的代码。
from selenium import webdriver
chromedriver = "C:/Lujing/chromedriver.exe"
browser = webdriver.Chrome(chromedriver)
browser.get("https://community-pm.p.cloud.sabrehospitality.com/pms-web-ui/login")
browser.implicitly_wait(10)
userElem = browser.find_element_by_id("spark-input_1")
userElem.send_keys("input user name") #enter user name in the quote
passwordElem = browser.find_element_by_id("spark-input_2")
passwordElem.send_keys("input password") #enter password in the quote
signin = browser.find_element_by_class_name('login-button spark-btn spark-btn--md spark-btn--primary spark-block--lte-sm spark-margin-bottom--md spark-pull-right--gte-sm')
type(signin)
signin.click()
我也曾尝试使用find_element_by_xpath("//*[@id='spark-input_1']")
,但我不断收到以下错误消息。
Traceback (most recent call last):
File "C:\Lujing\Python Scripts\PMS_report_downloads.py", line 9, in <module>
userElem=browser.find_element_by_id("spark-input_1")
File "C:\Users\Lujing.gao\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\Lujing.gao\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\Lujing.gao\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\Lujing.gao\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="spark-input_1"]"}
(Session info: chrome=80.0.3987.163)
Here is a screenshot of the source codes in the webpage
有人可以帮我吗?
答案 0 :(得分:0)
以下是为用户名字段输入值的可行解决方案。您可以弄清楚如何执行密码字段和提交按钮。注意我在geckodriver上遇到了问题。我不确定它是否适合您,但它适用于我的Chromedriver。
正如我在对您的帖子的评论中提到的那样,找不到元素的原因是因为shadowDOM。您可以使用一些JavaScript来传递该信息。请注意,在网站的未来页面中,您可能会遇到嵌套的shadowDOM,这将需要与下面类似的解决方案,但需要递归。
browser = webdriver.Chrome()
browser.get("https://community-pm.p.cloud.sabrehospitality.com/pms-web-ui/login")
shadow_root = browser.execute_script('return arguments[0].shadowRoot', browser.find_element_by_tag_name("sabre-shs-login"))
userElem = shadow_root.find_element_by_id('spark-input_1')
userElem.send_keys("input user name") #enter user name in the quote