python - 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")
解决方案
我还建议明确等待该元素。
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()
推荐阅读
- php - 从表单外部提交 textarea 内容
- java - 将 Konik 库添加到 Maven Web 服务项目
- vulkan - Vulkan vkCmdDrawIndexedIndirect 如何为每个内部绘制命令使用不同的纹理
- html - 如何将 svg 中的线性渐变作为 div 的背景颜色?
- c# - 我正在努力声明一个变量来引用 gameManager
- neo4j - 遇到给定节点时,Neo4j 停止搜索无向路径
- java - 如何使用 selenium webdriver 从 gmail 电子邮件内容中捕获 OTP 代码
- android - 检查 WorkRequest 之前是否已被 WorkManager Android 入队
- javascript - 任何人都知道如何使用 reactjs 登录 linkdIn
- google-chrome - Chrome 开发者控制台快捷键 CTRL Shift J 什么都不做