Today I wants to share Xpath using selenium. Xpath is a unique tool, which is better than other finding_element. These are the following element you can use:
find_element_by_id
find_element_by_name
find_element_by_xpath
find_element_by_link_text
find_element_by_partial_link_text
find_element_by_tag_name
find_element_by_class_name
find_element_by_css_selector
or multiply element
find_elements_by_id
find_elements_by_name
find_elements_by_xpath
find_elements_by_link_text
find_elements_by_partial_link_text
find_elements_by_tag_name
find_elements_by_class_name
find_elements_by_css_selector
I think to know XPath is really important.
The syntax of it is:
Xpath=//tagname[@attribute='value']
This is a HTML :
<html><body><p>Are you sure you want to do this?</p><a href="continue.html">Continue</a><a href="cancel.html">Cancel</a><form id="loginForm"><input name="username" type="text" /><input name="password" type="password" /><input name="continue" type="submit" value="Login" /><input name="continue" type="button" value="Clear" /><div class="search">This is new page<h1>Hello</h1>!!!!!</div></form></body></html>
- If you want to get the name for the username, you can try like this:
//input[@name='username']
- using chrome development tool to get xpath. The [1] is username, [2] is password ....[4]
//*[@id="loginForm"]/input[1]
//*[@id="loginForm"]//input[@name="username"]
- Full path using chrome development tool
/html/body/form/input[1]
you can see the input name for clear and login is the same "continue", if we want to get the clear button:
//input[@name='continue'][@type='button']
or
//*[@id="loginForm"]/input[4]
You can also use some function text(), or contain
If you use JUST text(), the string must be the same, else won't find it
//*[text()="str"]
//*[contains(text(),'str')]
if I want to find "continue", I can use this:
//*[text()="Continue"]
or
//*[text()="Cont"]
using (dot)
Sometimes when you used text() or contain() to find, but will not be able to find, you can use this method:
For example, this is Instagram following text, which can't find the following, you have to use this method.
//*[text()[contains(.,'str')]]
//*[contains(.,'str')]
this will search from the root to the current node.
Selenium with Xpath
inorder to use in selenium you have to use like this|:
driver.find_element_by_xpath('put-your-xpath-here').click()
No comments:
Post a Comment