Я написал фрагмент кода, который переходит на веб-сайт, ищет предмет, затем выбирает размер предмета и добавляет его в сумку.
После того, как предмет добавлен в сумку, я хочу ввести цикл while, чтобы он продолжал увеличивать количество предмета, пока оно не станет равным или превысит 200 фунтов стерлингов. Я понимаю, что цикл while будет лучшим методом для этого, так как я не знаю, сколько циклов я хочу делать.
Я считаю, что цикл следует вводить после добавления одного предмета в сумку, поскольку только на этом этапе я могу сказать количество предмета. В моем цикле, как я могу получить свой код для проверки цены количества предметов каждый раз, когда она увеличивается на +1.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Support.UI;
using OpenQA.Selenium.Interactions;
using System.Threading;
namespace Exercise1
{
class Exercise3
{
static void Main()
{
IWebDriver webDriver = new ChromeDriver();
webDriver.Navigate().GoToUrl("http://www.asos.com/men/");
webDriver.Manage().Window.Maximize();
webDriver.FindElement(By.XPath(".//input[@data-testid='search-input']")).SendKeys("nike trainers");
webDriver.FindElement(By.XPath(".//button[@data-testid='search-button-inline']")).Click();
WebDriverWait wait = new WebDriverWait(webDriver, TimeSpan.FromSeconds(5));
IWebElement country = wait.Until(ExpectedConditions.ElementExists(By.CssSelector("article img")));
webDriver.FindElement(By.CssSelector("article img")).Click();
IWebElement Size = webDriver.FindElement(By.XPath(".//select[@data-id='sizeSelect']"));
SelectElementFromDropDown(Size, "UK 10.5 - EU 45.5 - US 11.5");
webDriver.FindElement(By.XPath("//*[@data-bind='text: buttonText']")).Click();
webDriver.FindElement(By.XPath("//a[@data-testid='bagIcon']")).Click();
// I believe the while loop should be implemented here
int number = 200;
while (number > 200)
webDriver.Quit();
}
private static void SelectElementFromDropDown(IWebElement ele, string text)
{
SelectElement select = new SelectElement(ele);
select.SelectByText(text);
}
}
}
Он прекратится, как только сумма станет равной или превысит 200 фунтов стерлингов.
Вы знаете, как получить стоимость корзины? В этом случае вы можете сделать while( (get cart total) < 200)
Нет, как мне проверять стоимость сумки каждый раз при добавлении количества
Попробуйте прочитать значение метки, на которой указана общая цена на веб-сайте, и преобразовать его в int (так как это, скорее всего, будет строка)





Store the value of the item in a variable before starting the loop and creata a variable with initial value int i =1 and with every time loop runs increment the value by and multiply it by the original value and match is with the value with you fetch from the UI eveytime..
int i = 1
while(condition){
i++
//price for each iteration `enter code here`
i*price for 1 item = "value from the UI"
}
Где будет храниться стоимость? и как я могу получить значение из пользовательского интерфейса?
Код ниже можно добавить в то место, где вы прокомментировали // I believe the while loop should be implemented here
String price = webDriver.FindElement(By.XPath("//span[@class='bag-item-price bag-item-price--current']"))
.getAttribute("innerHTML");
int pricePerUnit = (int) Double.Parse(price.substring(1, price.Length - 1));
int qty = 1;
while (pricePerUnit * qty <= 200) {
qty++;
}
qty--;
IWebElement quantityDropDown = webDriver.FindElement(
By.XPath("//select[@class='bag-item-quantity bag-item-selector select2-hidden-accessible']"));
SelectElementFromDropDown(quantityDropDown, qty.ToString());
У меня есть 2 исключения для price.Length и Integer.toString (qty));
Как я могу изменить свой метод, чтобы он мог обрабатывать диапазон, поскольку это следующее исключение, которое я получаю
Можете ли вы указать строку, в которой вы получаете исключение
Я попытался запустить код IWebElement Qty = webDriver.FindElement (By.XPath ("// span [@ class = 'bag-item-pric e bag-item-price - current']")); SelectElementFromDropDown (Qty, «2»); просто чтобы увидеть, правильно ли работает раскрывающийся список. Я получаю исключение в моем методе selectElementFromDropDown. Элемент должен был быть выбран, но он был охвачен
Кол-во должно быть WebElement типа Select, а не типа span
Вы можете реализовать свой сценарий без использования циклов (цикл for / while). Я добавил логику ниже. Отрисовка некоторых элементов занимает больше времени. Итак, я бы посоветовал добавить явное условие везде, где это необходимо.
Пожалуйста, найдите обновленный код и ознакомьтесь со всеми комментариями для получения более подробной информации.
Основной метод:
IWebDriver webDriver = new ChromeDriver();
webDriver.Navigate().GoToUrl("http://www.asos.com/men/");
webDriver.Manage().Window.Maximize();
webDriver.FindElement(By.XPath(".//input[@data-testid='search-input']")).SendKeys("nike trainers");
webDriver.FindElement(By.XPath(".//button[@data-testid='search-button-inline']")).Click();
//Search Result rendering will take some times.So, Explicit wait is mandatory
WebDriverWait wait = new WebDriverWait(webDriver, TimeSpan.FromSeconds(5));
IWebElement country = wait.Until(ExpectedConditions.ElementExists(By.CssSelector("article img")));
webDriver.FindElement(By.CssSelector("article img")).Click();
IWebElement Size = webDriver.FindElement(By.XPath(".//select[@data-id='sizeSelect']"));
SelectElementFromDropDown(Size, "UK 10 - EU 45 - US 11");
webDriver.FindElement(By.XPath("//*[@data-bind='text: buttonText']")).Click();
//Add to cart takes some time.So, the below condition is needed
wait.Until(ExpectedConditions.ElementExists(By.XPath("//span[text()='Added']")));
webDriver.FindElement(By.XPath("//a[@data-testid='bagIcon']")).Click();
//Wait condition is needed after the page load
//wait.Until(ExpectedConditions.TitleContains("Shopping"));
wait.Until(ExpectedConditions.ElementExists(By.XPath("//select[contains(@class,'bag-item-quantity')]")));
//Extract the price from the cart
string totalPrice =webDriver.FindElement(By.XPath("//span[@class='bag-subtotal-price']")).Text;
//Extract the price amount by exluding the currency
double pricePerItem = Convert.ToDouble(totalPrice.Substring(1));
// Just hardcoded the expected price limit value
int priceLimit = 200;
double noOfQuantity = priceLimit / pricePerItem;
IWebElement qty =webDriver.FindElement(By.XPath("//select[contains(@class,'bag-item-quantity')]"));
//Quantity values are rounded off with nearest lowest value . Example, 5.55 will be considered as 5 quantity
SelectElementFromDropDown(qty, Math.Floor(noOfQuantity).ToString());
//After updating the quantity, update button will be displayed dynamically.So, wait is added and then update action is performed
wait.Until(ExpectedConditions.ElementExists(By.XPath("//button[@class='bag-item-edit-update']")));
webDriver.FindElement(By.XPath("//button[@class='bag-item-edit-update']")).Click();
Альтернативный подход с использованием цикла:
Я настоятельно рекомендую использовать описанный выше подход. поскольку количество будет увеличиваться один за другим каждый раз, пока предел цены не превысит 200
//Extract the price from the cart
string totalPrice = webDriver.FindElement(By.XPath("//span[@class='bag-subtotal-price']")).Text;
double currentTotalPrice = Convert.ToDouble(totalPrice.Substring(1));
double itemPerPrice = currentTotalPrice;
// Just hardcoded the expected price limit value
int priceLimit = 200;
int quantity = 1;
while(currentTotalPrice < priceLimit && priceLimit-currentTotalPrice > itemPerPrice)
{
wait.Until(ExpectedConditions.ElementExists(By.XPath("//select[contains(@class,'bag-item-quantity')]")));
IWebElement qty = webDriver.FindElement(By.XPath("//select[contains(@class,'bag-item-quantity')]"));
//Quantity values are rounded off with nearest lowest value . Example, 5.55 will be considered as 5 quantity
SelectElementFromDropDown(qty, (++quantity).ToString());
//After updating the quantity, update button will be displayed dynamically.So, wait is added and then update action is performed
wait.Until(ExpectedConditions.ElementExists(By.XPath("//button[@class='bag-item-edit-update']")));
webDriver.FindElement(By.XPath("//button[@class='bag-item-edit-update']")).Click();
wait.Until(ExpectedConditions.ElementExists(By.XPath("//span[@class='bag-subtotal-price']")));
var temp = webDriver.FindElement(By.XPath("//span[@class='bag-subtotal-price']")).Text;
currentTotalPrice = Convert.ToDouble(temp.Substring(1));
Console.WriteLine("Current Price :" + currentTotalPrice);
}
Как я могу изменить предельную цену, чтобы она увеличивалась только до тех пор, пока не превысила 200 фунтов стерлингов
Можете ли вы попробовать с приведенным выше фрагментом кода и поделиться журналами, если они есть. Я протестировал приведенный выше код, и он у меня работает нормально.
@ J.dockster: Здесь я жестко запрограммировал значение priceLimit как 200, и я вычисляю no of Quantity динамически как double noOfQuantity = priceLimit / pricePerItem; (Например, если цена за единичное количество составляет 30 фунтов стерлингов, а ожидаемое значение priceLimit равно £ 200, то количество не будет = 200/30 = 6,66. После округления значение 6 будет считаться отсутствием количества). Наконец, мы можем напрямую выбрать значение количества на основе указанного выше количества.
Хорошо, но если я захочу продолжать добавлять, пока не достигну более 200 фунтов стерлингов, возможно ли это?
Могу ли я сделать логическое значение int priceLimit> 200?
@ J.dockster: вы все еще можете увеличивать количество один за другим, и я обновил ответ альтернативным способом
I understand the while loop will be the best method for this as there isn't a set amount of loops I know I want to do.когда это остановится?