Selenium python get input value

How to enter value in input text field in Selenium Python?

In this tutorial, you will learn how to enter a value in an input text field in Selenium Python.

To enter a value in an input text field in Selenium Python, you can use send_keys() method of the element object.

Steps to enter value in input text field

  1. Find the input text field element in the web page using driver.find_element() method.
  2. Call send_keys() method on the input text field element, and pass the value that we want to enter in the input text field, as argument.
input_text_element.send_keys("Ram")

Example

In the following example, we initialize a Chrome webdriver, navigate to a specific URL that contains a form element with a couple of input text fields, take the screenshot, enter a value in the input text field whose id is «fname», and then take the screenshot again.

Python Program

from selenium import webdriver from webdriver_manager.chrome import ChromeDriverManager from selenium.webdriver.chrome.service import Service as ChromeService from selenium.webdriver.common.by import By # Setup chrome driver service = ChromeService(executable_path=ChromeDriverManager().install()) driver = webdriver.Chrome(service=service) driver.set_window_size(500, 500) # Navigate to the url driver.get('http://127.0.0.1:5500/index.html') # Find input text field input_text_fname = driver.find_element(By.ID, 'fname') # Take a screenshot before entering a value driver.save_screenshot("screenshot-1.png") # Enter a value in the input text field input_text_fname.send_keys("Ram") # Take a screenshot after entering a value driver.save_screenshot("screenshot-2.png") # Close the driver driver.quit()
  

My Form



screenshot-1.png

Selenium Python - Enter value in input text box - Example

screenshot-2.png

Selenium Python - Enter value in input text box

Summary

In this Python Selenium tutorial, we have given instructions on how to enter a value in an input text field, using send_keys() method.

Источник

How to get value in input text field in Selenium Python?

In this tutorial, you will learn how to get or read the value entered by a user in an input text field in Selenium Python.

Читайте также:  Имплементация интерфейсов в java

To get the value present in an input text field in Selenium Python, you can use get_attribute() method of the element object.

Steps to get the value present in input text field

  1. Find the input text field element in the web page using driver.find_element() method.
  2. Call get_attribute() method on the input text field element, and pass the attribute name ‘value’ to the method. The method returns the value present in the input text field.
value = input_text_element.get_attribute('value')

Example

In the following example, we initialize a Chrome webdriver, navigate to a specific URL that contains a form element with a couple of input text fields, take the screenshot, get the value present in the input text field whose id is «fname», and print the value to standard output.

Python Program

from selenium import webdriver from webdriver_manager.chrome import ChromeDriverManager from selenium.webdriver.chrome.service import Service as ChromeService from selenium.webdriver.common.by import By # Setup chrome driver service = ChromeService(executable_path=ChromeDriverManager().install()) driver = webdriver.Chrome(service=service) driver.set_window_size(500, 500) # Navigate to the url driver.get('http://127.0.0.1:5500/index.html') # Take a screenshot of the webpage driver.save_screenshot("screenshot.png") # Find input text field input_text_fname = driver.find_element(By.ID, 'fname') # Get the value in the input text field input_text_value = input_text_fname.get_attribute('value') print(input_text_value) # Close the driver driver.quit()
  

My Form



screenshot.png

Selenium Python - Get value in input text field

Summary

In this Python Selenium tutorial, we have given instructions on how to get the value in an input text field, using get_attribute() method.

Источник

Get value of an input box using Selenium (Python)

Note that there’s an important difference between the value attribute and the value property.

The simplified explanation is that the value attribute is what’s found in the HTML tag and the value property is what you see on the page.

Basically, the value attribute sets the element’s initial value, while the value property contains the current value.

You can read more about that here and see an example of the difference here.

If you want the value attribute, then you should use get_attribute:

If you want the value property, then you should use get_property

Though, according to the docs, get_attribute actually returns the property rather than the attribute, unless the property doesn’t exist. get_property will always return the property.

Pikamander2 6343

More Query from same tag

  • MCMC convergence in hierarchical model with (large) time^2 term in pymc3
  • Cornice schema validation with colanderalchemy
  • How to set up a hostkey file using ssh-ed25519 as a key for pysftp
  • pymongo — Why is Multiprocessing not faster
  • Python key generation strategy for URLs
  • How to concatenate two dataframes based on the particular columns?
  • Efficiently read all available bytes from binary stream in python (like C++ readsome)
  • How to read the tiles into the tensor if the images are tif float32?
  • What is Lock in Python _thread module?
  • MATLAB Engine API for Python. Error: MATLAB Engine for Python supports Python version
  • Python: How to search and replace parts of a json file?
  • Selenium keeps opening new window
  • How to write a program that mimics Fiddler by using tcpdump or from scratch?
  • Selenium xpath links with Python firefox driver not clicking
  • How can I tie value of a variable to the name of that variable?
  • Not Responding window when browser is loading + Text is not changing
  • Can’t apply style to Tkinter slider
  • Tensorflow reshape issue, ValueError: Cannot feed value of shape (1, 2) for Tensor u’Placeholder:0′, which has shape ‘(?, 1, 2)’
  • Can Microsoft Graph API be used with a desktop python script?
  • Efficient search in list of tuples
  • How to loop text file to create string of values
  • How to zip a list of tuple inside tuple
  • How convert the specific conversational files into columns and save it in python
  • Problems with launch qiskit
  • rendering in Visual Studio Code — Python
  • Pygame — rect disappears before I reach it
  • attempted relative import with no known parent package when running CrawlerProcess
  • 50013: Missing Permissions- Discord bot is unable to ban/kick even with the highest priority role, and every single permission given to them
  • How to get newest recording in Twilio?
  • Selenium printing same information repeatedly
  • Get value from a website using selenium in python
  • Multiple CSV Python sort
  • Python 2.7 formatting data for writing as csv
  • MT: Calculating METEOR Score of two different files
  • Encoding error on windows when code runs fine on linux
Читайте также:  Python django project import

Источник

Поиск HTML элементов

Как вы, возможно, уже поняли, чтобы управлять элементами страницы, нам нужно сначала найти их. Selenium использует так называемые локаторы, чтобы находить элементы на веб-странице.

В Selenium есть 8 методов которые помогут в поиске HTML элементов:

Вы можете использовать любой из них, чтобы сузить поиск элемента, который вам нужен.

Запуск браузера

Тестирование веб-сайтов начинается с браузера. В приведенном ниже тестовом скрипте запускается окно браузера Firefox, и осуществляется переход на сайт.

Используйте webdriver.Chrome и webdriver.Ie() для тестирования в Chrome и IE соответственно. Новичкам рекомендуется закрыть окно браузера в конце тестового примера.

Поиск элемента по ID

Использование идентификаторов — самый простой и безопасный способ поиска элемента в HTML. Если страница соответствует W3C HTML, идентификаторы должны быть уникальными и идентифицироваться в веб-элементах управления. По сравнению с текстами тестовые сценарии, использующие идентификаторы, менее склонны к изменениям приложений (например, разработчики могут принять решение об изменении метки, но с меньшей вероятностью изменить идентификатор).

Поиск элемента по имени

Атрибут имени используются в элементах управления формой, такой как текстовые поля и переключатели (radio кнопки). Значения имени передаются на сервер при отправке формы. С точки зрения вероятности будущих изменений, атрибут name, второй по отношению к ID.

Поиск элемента по тексту ссылки

Только для гиперссылок. Использование текста ссылки — это, пожалуй, самый прямой способ щелкнуть ссылку, так как это то, что мы видим на странице.

HTML для которого будет работать

Поиск элемента по частичному тексту ссылки

Selenium позволяет идентифицировать элемент управления гиперссылкой с частичным текстом. Это может быть полезно, если текст генерируется динамически. Другими словами, текст на одной веб-странице может отличаться при следующем посещении. Мы могли бы использовать общий текст, общий для этих динамически создаваемых текстов ссылок, для их идентификации.

Читайте также:  first-letter

HTML для которого будет работать

Поиск элемента по XPath

XPath, XML Path Language, является языком запросов для выбора узлов из XML документа. Когда браузер отображает веб-страницу, он анализирует его в дереве DOM. XPath может использоваться для ссылки на определенный узел в дереве DOM. Если это звучит слишком сложно для вас, не волнуйтесь, просто помните, что XPath — это самый мощный способ найти определенный веб-элемент.

HTML для которого будет работать

Некоторые тестеры чувствуют себя «запуганными» сложностью XPath. Тем не менее, на практике существует только ограниченная область для использования XPath.

Избегайте XPath из Developer Tool

Избегайте использования скопированного XPath из инструмента Developer Tool.

Инструмент разработчика браузера (щелкните правой кнопкой мыши, чтобы выбрать «Проверить элемент», чтобы увидеть) очень полезен для определения веб-элемента на веб-странице. Вы можете получить XPath веб-элемента там, как показано ниже (в Chrome):

Поиск HTML элементов

Скопированный XPath для второй ссылки «Нажмите здесь» в примере:

Источник

Оцените статью