Reputation: 20240
I wrote in Python a script which uses Selenium to auto-complete a form. It works with no issues.
I am very new to C# but I thought I would try and port it over so I can build a Windows executable to share it with a couple of non tech-savvy family members.
However, when I try what appears to be the same code, I get a timeout in C#.
As an example, I am trying to click a radio button:
HTML of radio button:
<input data-v-7af3e24c="" type="radio" id="condition-2" name="condition" class="govuk-radios__input" value="false">
Python (this works):
WebDriverWait(driver, max_wait).until(EC.presence_of_element_located(
(By.CSS_SELECTOR, '[id$=condition-2]'))).click()
However, when I try what I think is the same request in C#:
int elementLoadTime = 5; // Max 5 seconds for element to load
var wait = new WebDriverWait(driver, new TimeSpan(0, 0, elementLoadTime));
wait.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.ElementToBeClickable(By.CssSelector("[id$=condition-2]"))).Click();
This produces:
Exception thrown: 'OpenQA.Selenium.WebDriverTimeoutException' in WebDriver.dll
The strange thing is, I am able to select the element in C# using the full XPath, so the element is clearly loading, and it strongly suggests the problem is with my CSS selector query.
// This works
wait.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.ElementToBeClickable(By.XPath("/html/body/div[1]/div[2]/main/div/div/form/fieldset/div[2]/div/div/div[2]/label"))).Click();
However, obviously that is a very brittle way of writing the code which will break the moment the site changes slightly.
I have also tried "[id$='condition-2']"
and "[id$=\"condition-2\"]"
, to no avail.
Can anyone shed any light on what I am doing wrong?
Upvotes: 0
Views: 139
Reputation: 57
Instead of using:
By.CssSelector("[id$=condition-2]")
Just use:
By.Id("condition-2")
If you want to use Xpath instead, do two things. First, forget that there's an option in your browser to 'Copy Xpath' - just purge it from your mind. Second, use this Xpath instead:
By.Xpath("//input[@id=\"condition-2\"]")
Upvotes: 1