【发布时间】:2019-09-26 09:31:48
【问题描述】:
我正在做一个有趣的辅助项目来自动化网站https://10fastfingers.com/,以便 Selenium 自动完成网站的所有成就。您可以在我的存储库中找到我当前的代码:https://github.com/jasperan/pyfastfingers
但是,我遇到了登录页面的问题:
https://10fastfingers.com/login
Selenium 不允许我立即定位以下 HTML 标记,其对应的 xpath 值如下所示:
//*[@id="UserEmail"]
[//*[@id="UserPassword"]
似乎网站第一次没有正确加载它们,因为即使我手动检查这些(使用我自己的网络客户端、Firefox、Chrome 甚至 Chromium 但我自己启动...),我也会自动获得重定向到它的祖父母:
/html/body
当我手动找到此元素后,经过第二次检查后,我可以重定向到所需的电子邮件和密码元素。
但是,以编程方式,我不能这样做。无论我尝试定位元素多少次,它都无法正确定位,每次都会抛出以下异常:
File "pyfastfingers.py", line 112, in <module>
main()
File "pyfastfingers.py", line 100, in main
do_login(driver)
File "pyfastfingers.py", line 74, in do_login
password = driver.find_element_by_xpath('[//*[@id="UserPassword"]')
File "/home/j/.local/lib/python3.6/site-packages/selenium/webdriver/remote/webdriver.py", line 394, in find_element_by_xpath
return self.find_element(by=By.XPATH, value=xpath)
File "/home/j/.local/lib/python3.6/site-packages/selenium/webdriver/remote/webdriver.py", line 978, in find_element
'value': value})['value']
File "/home/j/.local/lib/python3.6/site-packages/selenium/webdriver/remote/webdriver.py", line 321, in execute
self.error_handler.check_response(response)
File "/home/j/.local/lib/python3.6/site-packages/selenium/webdriver/remote/errorhandler.py", line 242, in check_response
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.InvalidSelectorException: Message: invalid selector: Unable to locate an element with the xpath expression [//*[@id="UserPassword"] because of the following error:
SyntaxError: Failed to execute 'evaluate' on 'Document': The string '[//*[@id="UserPassword"]' is not a valid XPath expression.
(Session info: chrome=74.0.3729.169)
(Driver info: chromedriver=74.0.3729.6 (255758eccf3d244491b8a1317aa76e1ce10d57e9-refs/branch-heads/3729@{#29}),platform=Linux 4.18.0-21-generic x86_64)
下面是一些与我的登录功能相对应的代码:
driver.get('https://10fastfingers.com/login')
placeholder = driver.find_element_by_xpath('/html/body')
email = driver.find_element_by_xpath('//*[@id="UserEmail"]')
password = driver.find_element_by_xpath('[//*[@id="UserPassword"]')
email.send_keys(os.environ['FINGERS_EMAIL'])
password.send_keys(os.environ['FINGERS_PASSWORD'])
login_button = driver.find_element_by_id('login-form-submit')
login_button.click()
# Login complete
您可以在我的存储库中找到完整的代码。
【问题讨论】:
-
您的两个 xpath 不正确。使用
'//*[@id="UserEmail"]'和'//*[@id="UserPassword"]'重试。 -
使用
expected_conditions并等待这些元素加载。
标签: python html selenium automation