Selenium随机点击到Div的元素

huangapple go评论82阅读模式
英文:

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

Selenium随机点击到Div的元素

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&lt;WebElement&gt; 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 &#39;prdct-cntnr-wrppr&#39; class
int numDivs = driver.WebDriver.GetXpathCount(&quot;//*[@class=&#39;prdct-cntnr-wrppr&#39;]/div&quot;);
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(&quot;//*[@class=&#39;prdct-cntnr-wrppr&#39;]/div[{0}]&quot;, 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.

huangapple
  • 本文由 发表于 2020年9月3日 22:23:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/63725650.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定