英文:
Selenium random click to Div's
问题
我正在测试一个网站,我想随机获取一个 div 并点击它。
每个 div 都有产品的图片。
这个网站是:
https://www.trendyol.com/tum--urunler?q=bilgisayar&qt=bilgisayar&st=bilgisayar
英文:
I am testing a website and I want to get one of div's randomly and click to it.
Every Div has picture of product.
The website is this :
https://www.trendyol.com/tum--urunler?q=bilgisayar&qt=bilgisayar&st=bilgisayar
How can I do that ?
答案1
得分: 3
你可以使用以下代码:
List<WebElement> div_elements = driver.findElememts(By.xpath("//div[@class='p-card-wrppr']"));
Random random = new Random();
int num = random.nextInt(div_elements.size());
div_elements.get(num).click();
我已经假设您想要点击具有类名 p-card-wrppr 的任意 div 元素。如果您想要具有不同类名的 div 元素,请相应更改您的 xpath。
英文:
You can use below code:
List<WebElement> div_elements = driver.findElememts(By.xpath(“//div[@class=‘p-card-wrppr’]”));
Random random = new Random();
int num = random.nextInt(div_elements.size());
div_elements.get(num).click();
I have assumed you want to click any of the div with class p-card-wrppr. If you want divs with different class change your xpath accordingly.
答案2
得分: 1
我在Java方面了解不多,但你要做的是获取div的总数,然后生成一个介于1和N之间的随机数,并点击它。在C#中,代码看起来可能是这样的:
// 这将获取'class为prdct-cntnr-wrppr'的元素下的DIV数量
int numDivs = driver.WebDriver.GetXpathCount("//div[@class='prdct-cntnr-wrppr']/div");
Random ran = new Random();
int randomNum = ran.Next(1, numDivs); // 生成一个介于1和div数量之间的随机数
driver.FindElement(By.XPath(String.Format("//div[@class='prdct-cntnr-wrppr']/div[{0}]", randomNum))).Click();
请注意,这仅在您查看相同级别的div时有效。如果您想要子div,那就有些不同,但基本相同。
英文:
I'm not well versed in java, but what you would do is get the total number of divs, and then generate a random number between 1 and N, and click it. In c# it would look something like this:
// This will get you the number of DIVs under the 'prdct-cntnr-wrppr' class
int numDivs = driver.WebDriver.GetXpathCount("//*[@class='prdct-cntnr-wrppr']/div");
Random ran = new Random();
int randomNum = ran.Next(1,numDivs); // generates a random number between 1 and number of divs
driver.FindElement(By.XPath(String.Format("//*[@class='prdct-cntnr-wrppr']/div[{0}]", randomNum))).Click();
Note that this will only work if you're looking at the same level of divs. If you want sub-divs, then that's a little different, but more or less the same.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论