我有一个基本的自动化测试,我使用 selenium 和 cucumber 登录酒店预订网站,然后在登录后单击一个名为 wifi 复选框的复选框。我可以在登录页面上很好地输入用户名和密码,但是登录后,硒停止工作。我无法点击 wifi 按钮。我尝试了隐式等待,但这不起作用。
这是我的代码
const {By, Key, Builder} = require("selenium-webdriver");
require("chromedriver");
const {Before,Given,When,And,Then}=require('@cucumber/cucumber')
let driver = new Builder().forBrowser("chrome").build();
var {setDefaultTimeout} = require('@cucumber/cucumber');
setDefaultTimeout(60 * 1000);
Given('when you are on the login page', async function () {
await driver.get("https://automationintesting.online/#/admin")
});
When('you enter login credentails' , function () {
driver.findElement(By.id("username")).sendKeys("admin");
driver.findElement(By.id("password")).sendKeys("password");
driver.findElement(By.id("doLogin")).click();
});
When('your logged in ',{ implicit: 3000 },async ()=> {
driver.manage().setTimeouts({ implicit: 3000 });
await driver.findElement(By.id("wifiCheckbox")).click();
});
Then('you should be on the profile page', function () {
driver.getCurrentUrl()
});
下面的代码工作得很好
driver.findElement(By.id("username")).sendKeys("admin");
driver.findElement(By.id("password")).sendKeys("password");
driver.findElement(By.id("doLogin")).click();
下面的代码不起作用
driver.manage().setTimeouts({ implicit: 3000 });
await driver.findElement(By.id("wifiCheckbox")).click();
我收到请求失败 403 错误
403错误通常被称为“禁止”错误,通常表示您没有权限访问网站上的特定资源。对于您的情况,该网站可能会阻止或限制您登录后尝试单击的资源的访问。
您可以尝试诊断并可能解决问题的一些方法:
1 - 等待元素可见性: 您应该显式等待“wifiCheckbox”元素在页面上变得可见,然后再尝试单击它,而不是设置隐式超时。您可以使用 WebDriverWait 类来实现此目的。这是一个例子:
const { By, Key, Builder, until } = require("selenium-webdriver");
// ...
When('your logged in', async () => {
const wifiCheckbox = await driver.wait(until.elementLocated(By.id("wifiCheckbox")));
await wifiCheckbox.click();
});
2 - 用户代理或标头: 某些网站可能会阻止来自无头浏览器或某些用户代理的请求。您可以尝试设置用户代理来模拟真实的浏览器。例如:
driver.executeScript("return navigator.userAgent");