首页 > 解决方案 > Selenium 使用驱动程序元素登录网站

问题描述

下面我附上了用户名和密码的html代码:

用户名:

<input class="form-control input-sm snl-widgets-input-text snl-selectable action" data-part="input" data-bind="snlEnable: enable,value: value,valueUpdate: valueUpdate,visible: visible,css: { 'tags': enableTagsInput, 'clear': enableClear, 'search': enableSearch, 'action': externalActionVisible, 'pseudoTags': enablePseudoTags },hasFocus: hasFocus,attr: { type: type, name: name, placeholder: placeholder, maxlength: maxlength }" type="text" name="username" placeholder="Email address" maxlength="524288">

密码:

<input class="form-control input-sm snl-widgets-input-text snl-selectable action" data-part="input" data-bind="snlEnable: enable,value: value,valueUpdate: valueUpdate,visible: visible,css: { 'tags': enableTagsInput, 'clear': enableClear, 'search': enableSearch, 'action': externalActionVisible, 'pseudoTags': enablePseudoTags },hasFocus: hasFocus,attr: { type: type, name: name, placeholder: placeholder, maxlength: maxlength }" type="password" name="password" placeholder="Password" maxlength="524288">

我正在使用python 3.7。

使用右键单击并询问 xpath 时提供的以下 xpath 时出现“无法定位元素”错误:

username = driver.find_element_by_xpath("//*[@id=applicationHost]/div/div[2]/div[2]/div[4]/div[11]/div/div[2]/div[1]/div/form/div/div/div/div[3]/div[2]/div/div[1]/div[1]/div[1]/input")
password = driver.find_element_by_xpath("//*[@id=applicationHost]/div/div[2]/div[2]/div[4]/div[11]/div/div[2]/div[1]/div/form/div/div/div/div[3]/div[2]/div/div[1]/div[1]/div[2]/input")

标签: pythonseleniumbuttonclick

解决方案


我还建议明确等待该元素。

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
driver = webdriver.Chrome()
url="http://www.example.com"#your url here
driver.get(url)
element=WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.XPATH ,'//img[starts-with(@id,'removeImage_')]')))
#or '//img[contains(@id,'removeImage_')]'
element.click()

推荐阅读