Python 在selenium上找不到部分id
大家好 我正在尝试查找具有动态ID的元素,但是!无论我做什么,除了无接触的例外都被系统地提出 这是我的代码:Python 在selenium上找不到部分id,python,selenium,selenium-webdriver,Python,Selenium,Selenium Webdriver,大家好 我正在尝试查找具有动态ID的元素,但是!无论我做什么,除了无接触的例外都被系统地提出 这是我的代码: try: driver.get('http://www.website.com/') usr = driver.find_element_by_css_selector("a[id*='txtEmail']") pwd = driver.find_element_by_css_selector("a[id*='txtPassword']") usr.se
try:
driver.get('http://www.website.com/')
usr = driver.find_element_by_css_selector("a[id*='txtEmail']")
pwd = driver.find_element_by_css_selector("a[id*='txtPassword']")
usr.send_keys(username)
pwd.send_keys(password)
driver.find_element_by_css_Selector("a[id*='btnLogin']").click()
if (driver.find_element_by_css_Selector("a[id$=lnkLogOut]")):
log.info("Successfully connected")
else:
log.error("Login failed - Cannot login to the website - Wrong username/password ?")
except NoSuchElementException:
log.error("Cannot find element needed on the login page")
except TimeoutException:
log.error("Cannot reach the website in time")
except:
log.error("Error occurred during the login attempt: {}".format(sys.exc_info()))
以下是html表单:
<td>Email/Username:</td>
<td><input name="ctl00$cph1$Login1$txtEmail" id="ctl00_cph1_Login1_txtEmail" style="width:160px;" type="text"></td>
<td>Password:</td>
<td><input name="ctl00$cph1$Login1$txtPassword" id="ctl00_cph1_Login1_txtPassword" style="width:160px;" type="password"></td>
<td><input name="ctl00$cph1$Login1$btnLogin" value="Login" id="ctl00_cph1_Login1_btnLogin" class="fancy" with="80px;" style="height:28px;" type="submit"></td>
问题出在哪里?有什么想法吗
编辑:以下行引发错误:
usr = driver.find_element_by_css_selector("a[id*='txtEmail']")
pwd = driver.find_element_by_css_selector("a[id*='txtPassword']")
根据提供的HTML代码标记,用户名、密码和提交按钮均为“输入”,但代码中使用了“a”。这就是问题的原因 根据评论,下面的一个是有效的
usr = driver.find_elements_by_xpath('//*[contains(@id, "txtEmail")]')
因为这里的标记“a”没有在xpath中使用,而是使用“*”表示任何标记,所以在这里输入
我期待注销按钮也有标签“输入”作为注销元素的HTML代码没有提供。所以请检查并创建正确的css或xpath,以便解决超时异常
谢谢,,
Murali要遵循@Murali关于
a
与输入
的观点,您只需修复CSS选择器即可:
usr = driver.find_element_by_css_selector("input[id*=txtEmail]")
pwd = driver.find_element_by_css_selector("input[id*=txtPassword]")
您也可以使用“结束于”检查而不是“包含”:
Toshiro,在不自称是Python专家的情况下(我想我只在stackoverflow答案中编写了Python代码),我建议您在尝试中注释掉除第一行和测试之外的所有代码。如果没有得到异常,则取消对第二行的注释并进行测试。在搜索结束时,您将找到导致错误的行。当您知道哪一行抛出了错误时,请编辑您的问题以获得更好的答案。您没有尝试添加waitForElement吗?您没有尝试通过id访问它吗?请将完整的
xpath
暴露到元素中您正在尝试使用css选择器,但是如果元素是动态的,您应该使用xpath选择器(find_by_xpath)好的,我尝试了以下行:usr=driver.find_elements_by_xpath('/*[contains(@id,“txtmail”)]),它成功了!但是,我不明白为什么使用css选择器时,这无法工作,因为我已经用“*”设置了参数,表示“包含”(cf.[id*='txtEmail'])。谢谢您的总结:)好的,我现在更明白为什么了。谢谢你的解释!
usr = driver.find_element_by_css_selector("input[id*=txtEmail]")
pwd = driver.find_element_by_css_selector("input[id*=txtPassword]")
usr = driver.find_element_by_css_selector("input[id$=txtEmail]")
pwd = driver.find_element_by_css_selector("input[id$=txtPassword]")