Reputation: 1
I am trying to login into Instagram using C# and Selenium but the website doesn't have an ID for the buttons. How else would I go about this? I tried using XPath but don't know much about it. Here is a sample of my code so far.
IWebDriver fox = new FirefoxDriver();
fox.Navigate().GoToUrl("http://www.instagram.com");
IWebElement email = fox.FindElement(By.XPath("//i[contains(@class, '_k6cv7')]"));
Upvotes: 0
Views: 1572
Reputation: 549
Try this:
IWebDriver fox = new FirefoxDriver();
fox.Navigate().GoToUrl("http://www.instagram.com");
IWebElement email = fox.FindElement(By.CssSelector("input[name='username']"));
email.Sendkeys('[email protected]');
Upvotes: 0
Reputation: 25645
What you want to do is to find something unique about the element you want and use that to locate it. An id is generally ideal but, as you have seen, many elements that we might want to find don't have them so we have to rely on other attributes of the element. You can look for classes, as you did, or name or any other attribute. I generally use CSS selectors to find elements. I'll give you a couple examples and then put a couple links at the bottom that you can review and refer to later.
The Email INPUT
<input type="text" class="_kp5f7 _qy55y" aria-describedby="" aria-label="Email"
aria-required="true" autocapitalize="off" autocorrect="off" name="email"
placeholder="Email">
By Class
// INPUT with class (indicated by .) _kp5f7
driver.FindElement(By.CssSelector("input._kp5f7"));
You could use By.ClassName()
but that will give you any element type, INPUT
, P
, whatever. With this, you can accomplish the same but be more specific. You generally want to be as specific as possible. Doing this will minimize your locators breaking with future changes to the site.
By Attribute
// INPUT with attribute 'name' equal to 'email'
driver.FindElement(By.CssSelector("input[name='email']"));
The general form of the attribute search is TAG[ATTRIBUTE_NAME='ATTRIBUTE_VALUE']
. You can do a LOT more than just this but this is a really common CSS Selector.
Upvotes: 2
Reputation: 21
The classes on the buttons are generated so you won't find them using the class.
What you should do is to looks at something you could find, like that the "aria-label" is "username" (similar for password), and that the text on the button is "Log in".
You could also find the xpath using chrome (debug -> right click element -> copy -> xpath). The login field will give you something like
//*[@id="react-root"]/section/main/article/div[2]/div[1]/div/form/div[1]/input
Upvotes: 1