Selenium使用驱动程序元素登录网站

时间:2019-02-05 18:53:51

标签: python selenium button click

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

USERNAME:

<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")

3 个答案:

答案 0 :(得分:1)

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

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()

答案 1 :(得分:0)

使用您发布的摘录,我可以建议您:

from selenium.webdriver.common.by import By
driver.find_element(By.ID, "removeImage_E61858CD-F1F9-42BD-8848-8CB6B42ED2FE")

另一种方法可能是使用xPath。检索xPath的多种方法之一是在浏览器(即firefox)中打开它,右键单击元素,然后检查(Q),Copy,xPath,然后使用xpath:

driver.find_element(By.XPATH, 'your[4]/xPath/to[2]/element')

如果要单击元素,请在最后添加click():

driver.find_element(By.ID, "removeImage_E61858CD-F1F9-42BD-8848-8CB6B42ED2FE").click().

我不能为您推荐一个不错的教程,但是您可以在这里找到documentation

答案 2 :(得分:0)

您可以通过名称找到元素...

username = driver.find_element_by_name('username')
password = driver.find_element_by_name('password')