python selenium登录会话错误:TimeoutException:消息:

2024-09-27 21:29:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图使用python selenium登录,下面是我的代码:

from selenium import webdriver 
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait #as wait
from selenium.webdriver.common.by import By 
from selenium.webdriver.support import expected_conditions as ec
from selenium.common.exceptions import TimeoutException
option = webdriver.ChromeOptions()
option.add_argument(“ — incognito”)
decanter = webdriver.Chrome(executable_path=chromedriver_path, chrome_options=option)
BASE_URL = 'www.decanter.com/wine-reviews/search#order[updated_at]=desc&page={0}'
decanter.get("http://"+BASE_URL.format(1))
delay_sec = 1
decanter.find_element_by_css_selector("button.secondary").click()

直到这里,一切都正常了,上面最后一行代码打开了弹出的登录窗口,如屏幕截图所示: enter image description here

我试图登录的以下代码遇到了“TimeoutException:Message:”错误。在

^{pr2}$

我试过the solution here,它抛出了相同的错误。等待的时间和路径也不是问题,我是肯定的。在

进一步的尝试和错误消息包括:

>>> WebDriverWait(decanter, delay_sec).until(ec.element_to_be_clickable((By.XPATH, "//label[@class='inputlabel' and contains(.,'E-mail')]//following::p[1]/input[@type='text']"))).send_keys(USER)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Users/sheng/anaconda/lib/python2.7/site-packages/selenium/webdriver/support/wait.py", line 80, in until
raise TimeoutException(message, screen, stacktrace)
selenium.common.exceptions.TimeoutException: Message: 

Tags: 代码fromimportsupportasselenium错误common
2条回答

当您试图将文本发送到useridpasswd字段时,您需要使用子句^{},而不是expectedconditions子句^{}

USER = "userid"
PASSWORD = "passwd"
WebDriverWait(decanter, delay_sec).until(ec.element_to_be_clickable((By.XPATH, "//label[@class='inputlabel' and contains(.,'E-mail')]//following::p[1]/input[@type='text']"))).send_keys(USER)
decanter.find_element_by_xpath("//p[@class='input-group']/input[@type='password']").send_keys(PASSWORD)

注意:在遍历DOM时是否使用CSS/XPath没有最佳实践。CSS和XPath都有各自的优缺点。在


更新

正如我在评论中提到的,根据您更新的HTML快照,元素位于一个<iframe>标记中。因此,您必须按如下方式切换到所需的帧:

^{pr2}$

你的定位器有点不对劲。下面的代码应该可以工作。在

wait = WebDriverWait(decanter, delay_sec)
wait.until(EC.frame_to_be_available_and_switch_to_it(By.CSS_SELECTOR,"iframe[id^='piano-id-']"))
wait.until(ec.visibility_of_element_located((By.CSS_SELECTOR, 'input[fieldloginemail]'))).send_keys(USER)
decanter.find_element_by_css_selector('input[fieldloginpassword]').send_keys(PASSWORD)
decanter.find_element_by_css_selector('button[actionlogin]').click()
# once you are done with the content inside the iframe, switch context back to default
decanter.switch_to.default_content()

注意:将xpath与几个级别一起使用不是一个好主意,尤其是那些以HTML标记开头的级别。即使对DOM做了很小的更改,它们也很可能会中断。在

相关问题 更多 >

    热门问题