How to fetch values from a webelement in Selenium with python?


We can fetch values from a webelement in Selenium with the help of the methods listed below −

  • Using the text method.

    This will give the inner text of the webelement. It basically gives us the visible text on the screen and its sub element if any. This method will also remove all the forward and backward white spaces.

  • Using the Javascript executor.

    Javascript Document Object Model can work with any of the elements on the page. Javascript works on the client side and performs actions on the web page. Selenium can execute a Javascript script with the help of execute_script() method. We can fetch the values from a webelement with the help of this method.

Example

Code Implementation with text method

from selenium import webdriver
#browser exposes an executable file
#Through Selenium test we will invoke the executable file which will then #invoke #actual browser
driver = webdriver.Chrome(executable_path="C:\chromedriver.exe")
# to maximize the browser window
driver.maximize_window()
#get method to launch the URL
driver.get("https://www.tutorialspoint.com/index.htm")
#to refresh the browser
driver.refresh()
# identifying the edit box with the help of css
driver. find_element_by_css_selector("input[class='gsc-input']").
send_keys("Selenium")
# print the entered text in the console
print(driver. find_element_by_css_selector("input[class='gsc-input']").
text)
#to close the browser
driver.close()

Code Implementation with Javascript executor.

from selenium import webdriver
#browser exposes an executable file
#Through Selenium test we will invoke the executable file which will then #invoke #actual browser
driver = webdriver.Chrome(executable_path="C:\chromedriver.exe")
# to maximize the browser window
driver.maximize_window()
#get method to launch the URL
driver.get("https://www.tutorialspoint.com/index.htm")
#to refresh the browser
driver.refresh()
# identifying the edit box with the help of css
driver. find_element_by_css_selector("input[class='gsc-input']").
send_keys("Selenium")
# print the entered text in the console with Javascript executor
print(driver.execute_script(
'return document.getElementsByName("search")[0].value'))
#to close the browser
driver.close()

Updated on: 29-Jul-2020

692 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements