Sumit Jha Sumit Jha - 5 months ago 9
Python Question

Locating web element using selenium in python

I am trying to find an element in the web page using selenium. when I "right click" on the web element and inspect, I can find the html code in the console. However when I copy the xpath of the same element from the console and try to execute it in firepath, it says "No matching nodes". Why is it so and how can I fix this ?

Here is the HTML of the element.

<input id="mobile" type="text" onchange="javascript:dispLocMob(this);
"onkeydown="javascript:dispLocMob(this);
"onkeyup="javascript:dispLocMob(this);" value="" maxlength=
"10" placeholder="Mobile Number" name="mobile">


And this is what I am doing:

receiverMobileElement = browser.find_element_by_xpath('//*[@id="mobile"]')


Please help.

Answer

Why using xpath when you can find the element by unique id?

from selenium import webdriver

browser = webdriver.Firefox()
browser.get('http://example.com')

target_element = browser.find_element_by_id('mobile')