I want to build a bot to bets roulette with c#, I'm using selenium to find the numbers and click on them. I'm having 2 problems, the first problem is when I inspect for numbers game screen not visible in the inspection screen chromedriver inspection, normal chrome inspect the second problem I tried firefox instead of chrome, all things looks fine but when I try find by XPath I'm getting this error
OpenQA.Selenium.NoSuchElementException: 'Unable to locate element: /html/body/div[4]/div/div/div/div2/div/div[6]/div2/div/div2/div/div1/div/div1/div/svg/g/rect[20]'
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
IWebDriver chrome = new ChromeDriver();
IWebDriver firefox = new FirefoxDriver();
private void Form1_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
chrome.FindElement(By.XPath("/html/body/div[4]/div/div/div/div[2]/div/div[6]/div[2]/div/div[2]/div/div[1]/div/div[1]/div/svg/g/rect[20]")).Click();
}
private void button2_Click(object sender, EventArgs e)
{
chrome.Navigate().GoToUrl("https://tulipbet328.com/");
}
I just want to click on any number
CodePudding user response:
As per the xpath - /html/body/div[4]/div/div/div/div[2]/div/div[6]/div[2]/div/div[2]/div/div[1]/div/div[1]/div/svg/g/rect[20]
, the element is in an svg
tag.
Below is the syntax to interact with svg
tag elements.
//*[local-name()='svg'] or //*[name()='svg']
The xpath should be something like this:
...//*[name()='svg']//*[name()='g']//*[name()='rect']
Instead of Absolute xpath go for Relative xpaths. And apply some waits, either Implicit or Explixct.
CodePudding user response:
As per the xpath within the error message:
//html/body/div[4]/div/div/div/div2/div/div[6]/div2/div/div2/div/div1/div/div1/div/svg/g/rect[20]
It's quite evident that the desired element is a <rect>
element within it's parent <g>
tag which is within it's parent <svg>
tag.
Solution
To click on the 20th element you can use either of the following Locator Strategies:
CssSelector
:driver.FindElement(By.CssSelector("svg g rect:nth-child(20)")).Click();
or
driver.FindElement(By.CssSelector("svg g rect:nth-of-type(20)")).Click();
XPath
:driver.FindElement(By.XPath("//*[name()="svg"]//*[name()="g"]//*[name()="rect"][20]")).Click();
or
driver.FindElements(By.XPath("//*[name()="svg"]//*[name()="g"]//*[name()="rect"]"))[20].Click();
Update
To address OpenQA.Selenium.NoSuchElementException
you have to induce WebDriverWait for the desired ElementToBeClickable()
and you can use either of the following Locator Strategies:
CssSelector
:new WebDriverWait(driver, TimeSpan.FromSeconds(20)).Until(ExpectedConditions.ElementToBeClickable(By.CssSelector("element_css"))).Click();
XPath
:new WebDriverWait(driver, TimeSpan.FromSeconds(20)).Until(ExpectedConditions.ElementToBeClickable(By.XPath("element_xpath"))).Click();
References
You can find a couple of relevant detailed discussions in: