我正在尝试自动化使用带有selenium脚本的j_security_check提交表单的登录方案
以下是html代码:
<form name="getuserin" action="j_security_check" method="POST">
<table width="45%" align="left">
<tr>
<td align="left">Uname</td>
<td><input type="text" name="j_username"></td>
</tr>
<tr>
<td align="right">Passkey</td>
<td><input type="password" name="j_password"></td>
</tr>
</table>
<br>
<center><input type="submit" name="action" value="Login"></center>
</form>
Selenium代码
WebDriver driver = new FirefoxDriver();
driver.findElement(By.name("j_username")).sendKeys("validuser");
driver.findElement(By.name("j_password")).sendKeys("password");
driver.findElement(By.name("action")).click();
脚本成功运行,没有错误。我面临的问题是在运行脚本时没有执行登录操作,它确实输入了详细信息并单击了按钮。每当我尝试手动使用相同的凭据登录时,它都可以!我已经尝试过使用Internet Explorer和Firefox的方案。
答案 0 :(得分:0)
您是否尝试在点击按钮后设置制动点并查看它是否已登录?
我的建议是:
在第二种情况下,您必须等到页面及其所有脚本都已加载。在考虑如何操作之前,尝试在单击此按钮之前设置简单的线程休眠2秒。
如果它有帮助那么你必须找出处理这个按钮的东西,并等到它被加载。
答案 1 :(得分:0)
尝试此代码:
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.common.exceptions import NoSuchElementException
from itertools import cycle
import time
#importing various modules for added functionality
browser = webdriver.Firefox()
browser.get("http://www.example.com")
#creates browser object
#b.o. makes GET request to specified site
username = browser.find_element_by_id("email")
password = browser.find_element_by_id("password")
##looks for the html element "email" on above site
##looks for the html element "password" on above site
with open('creds.txt', 'r') as fp:
credentials = [x.strip().split(':') for x in fp.readlines()]
for uname,pwd in cycle(credentials):
username.send_keys(username from creds.txt file)
password.send_keys(password from creds.txt file)
##send username from file as email element value
##send password from file as password element value
login_attempt = browser.find_element_by_id("signInBtn")
login_attempt.click()
##looks for the html element "signInBtn" on above site
##simulates clicking of button
time.sleep(2)
title = browser.title
print title
#find the title of the html page and print it
welcome = browser.find_element_by_id("specific_element")
welcome_text = welcome.text.split()[1]
read_welcome = welcome_text.encode('utf-8')
#after successful login, look for element that is only present after successful login
#Welcome, <name>; only want the name here
#name was displaying in unicode for some reason, this converts the name as a normal string
if 'specific_string' in title:
#if string found in title variable
print "Login Sucessful for %r " % read_welcome
#"Login Successful for <name>"
browser.get("http://www.link_to_sign_out")
#simulate signing out
elif 'specific_string' not in title:
#if string not found in title variable
print "Sign In failed.."
#"Sign In failed.."
browser.get("http://www.link_to_sign_out")
##simulate signing out
else:
print 'Error..'
#If neither condition is met "Error" is printed
browser.close()