Selenium get attribute text python

Get Text Attribute CSS value & click Operations in Python Selenium

Everything on the website is a web element. We usually work with elements like text bar, button, menus, sub-menus, radio button, headers, footer, links, plain texts, forms so on.

W hen we do perform tests manually, we tend to click elements and will observe the behaviors, and we will set the values, and we will observe the conditions, and we will have our own checkpoints.

Selenium also provides the capability to test these kinds of actions; we can also retrieve the values from the elements to check colors and sizes as selenium cannot perform visual testing.

Click in selenium python bindings

We can perform a clicking operation using selenium python, before performing the click operation we have to find the elements using locators uniquely.

The height and width of the element must be more than 0px to click the element in selenium python. If the element is not enabled and if you perform a click on it, selenium throws InvalidElementStateException.

The below program performs a click on the ‘About’ link on the google page at the bottom

#CherCherTech # import the webdriver from selenium import webdriver # set exe path and open the browser. driver = webdriver.Chrome(executable_path=r'D:/PATH/chromedriver.exe'); # open website driver.get("https://google.com") driver.find_element_by_link_text("About").click()

Sendkeys in selenium python

sendKeys method sets text into an editable element (text bar, text area, button) without replacing the previously available content.

If you use more than one sendkeys on a field then selenium appends all of them; selenium will not replace the existing value when we use sendKeys.

#CherCherTech # import the webdriver from selenium import webdriver # set exe path and open the browser. driver = webdriver.Chrome(executable_path=r'D:/PATH/chromedriver.exe'); # open website driver.get("https://google.com") driver.find_element_by_name("q").send_keys("Chercher Tech")

Clear an element in selenium python

If we want to set values to a text field, we have to clear the field and set the value using sendkeys.

clear() method will help the user to clear the field on the webpage, if we do not clear a field then also selenium will not throw any exception, but it just appends the new value with the old value.

# open website driver.get("https://google.com") driver.find_element_by_name("q").send_keys("Chercher Tech") # clear the field driver.find_element_by_name("q").clear() # set the value driver.find_element_by_name("q").send_keys("CherTech")

Submit

submit() method in selenium python submits a form. Users can use it only along with form or with form elements only.

Читайте также:  Удалить несколько символов строки php

submit() method clicks a button is a misconception; it works only when that particular button is associated with the form.

# submit the form driver.find_element_by_name("value").submit()

Get Text of an Element in Python Selenium

text variable present in the driver will fetch the values of the text, not only the current element text but also the text of other elements inside that element.

# open website driver.get("https://google.com") # get the text print("Text retrieved : "+ driver.find_element_by_link_text("About").text)
Output : Text retrieved : About

Get Attribute of an Element in selenium python.

get_attibute() method fetches the value of an attribute, in HTML code whatever is present on the left side of ‘=’ is an attribute, the value on the right side is an Attribute value

# open website driver.get("https://google.com") # get the title attribute print("Title of searchbar : "+ driver.find_element_by_id("q").get_attribute("title"))
Output : Title of searchbar : Search

Insight about get Attributes:

Below are few insights from my experience about the get attribute.

  • Selenium returns the attribute present at the time of the query if the attribute value changes after the query then selenium will not return the new value.
  • getAttibute() returns blank as a value if the attribute is not set to any value (exception for boolean values).
  • getAttibute() returns ‘true’ in case if you are searching for a boolean value, and the value is not set.
  • Few Boolean attribute examples: checked, readonly, required, multiple, complete so on.
  • getAttibute() returns ‘null’ if there no such attribute

Get CSS Value in selenium python

value_of_css_property method in selenium python fetches the value of a CSS property of a web element in selenium python bindings, and we have to pass CSS property, which selenium binding have to fetch.

Whenever you want to retrieve any CSS property, you should check the property name in the Computed tab and pass the value to the method.

# open website driver.get("https://google.com") # get the css value cssValue = driver.find_element_by_name("q").value_of_css_property("font-size") print("font size searchbar : "+ cssValue)
Output : font size searchbar : 16px

CSS values depend on the browser; you may not get the same values for all the browser, below are few such examples

Few browsers may show 1px and others may show 1 px [ there is space indifference ]

Few browser may show rgba(0, 123, 255, 1) and other may show rgb(0, 123, 255) [ rgb and rgba difference].

Get Size of an Element in selenium python.

size property present in selenium determines the size of an element, size consists of two values width and height which are the sum of respective attributes.

Читайте также:  Синхронность и асинхронность python

width-get-size-Selenium-webdriver

Width = margin-left + margin-right + padding-left + padding-right + actual width;

height-get-size-selenium-webdriver

Height = margin-top + margin-bottom + padding-top + padding-bottom + actual height;

The above images are only for info purpose; the size variable returns the dictionary containing height a

# open website driver.get("https://google.com") # get the css value sizeOfElement = driver.find_element_by_name("q").size print("Width of the searchbar : ", sizeOfElement["width"]) print("Height of the searchbar : ", sizeOfElement["height"])
Output : Width of the searchbar : 403 Height of the searchbar : 34

is_displayed in selenium python

is_displayed() method in selenium python verifies and returns a boolean value based on the state of the element, whether it is displayed or not .

If there is no such attribute as hidden, selenium binding considers that the element is displayed (visit Boolean Attribute for details) and returns true.

# open website driver.get("https://google.com") # get the css value isDisplayed = driver.find_element_by_name("q").is_displayed() print("Is Searchbar Displayed : ", isDisplayed)
Output : Is Searchbar Displayed : True

is_enabled in selenium python

is_enabled() method in selenium python verifies and returns a boolean value based on the state of the element, whether it is enabled or not.

If there is no such attribute as enabled, python selenium considers that the element is enabled (visit Boolean Attribute for details) and returns true.

# open website driver.get("https://google.com") # element enabled isEnabled = driver.find_element_by_name("q").is_enabled() print("Is searchbar enabled : ", isEnabled)
Output : Is searchbar enabled : True

is_selected in selenium python

is_selected() verifies if an element is selected or not. is_selected() method returns a boolean value, true if the element is selected and false if it is not.

It is widely used on checkboxes, radio buttons, and dropdowns in selenium bindings.

# open website driver.get("https://chercher.tech/selenium-webdriver-sample") # get the css value isSelected = driver.find_element_by_xpath("//input[@id='selected']").is_selected() print("Is checkbox selected : ", isSelected)
Output : Is checkbox selected : ", False

Location of the element in selenium python

location property in selenium bindings fetches the x and y coordinates of the element. This property returns the dictionary as a return value.

driver.get("https://google.com") # get location locate = driver.find_element_by_name("q").location print("x value: ", locate["x"]) print("y value: ", locate["y"])
Output : x value: 290 y value: 323
Recommended Readings

I am Pavankumar, Having 8.5 years of experience currently working in Video/Live Analytics project.

Источник

The getAttribute() Function in Selenium Python

The getAttribute() Function in Selenium Python

  1. the getAttribute() Function in Selenium Python
  2. Advantages of the getAttribute() Function in Selenium Python

The Python module for Selenium is developed to deliver an automated testing process. The Selenium Python bindings include a simple API for writing Selenium WebDriver functional/acceptance tests.

Having the ability to move is not much beneficial. We want to interact with the pages, or more precisely, the HTML pieces consisting of a page.

Читайте также:  Тег IMG

This article will explain using Selenium’s getAttribute() method.

the getAttribute() Function in Selenium Python

The getAttribute() method can retrieve element properties, such as an anchor tag’s href attribute. This function will initially attempt to return the value of a specified property.

If no such property exists, the attribute’s value with the same name is returned. However, none is returned if no attributes exist in an element.

What Is an Attribute

An attribute in HTML defines the properties of an element. Attributes comprise name-value pairings, which means that each attribute has a value and a name.

Their values are encased in double quotes and are provided in the opening tag. HTML attributes include the following:

As from the above example, HTML tags get a variety of properties and values. For example, the input tag had many attributes such as class , style , placeholder , type , name , and id .

There is a number in double quotes for each property. Now that we understand what an attribute means for an HTML web element or how it appears let’s check why the getAttributes() method is useful.

Advantages of the getAttribute() Function in Selenium Python

Consider a situation where we must double-check the placeholder content on an input field, the picture source, and the field size. The getAttribute() method solves this problem in this situation.

To obtain the value of an attribute, locate the web element that holds it and use the getAttribute() method.

Let’s discuss the syntax of this method in a real example, as shown below.

# python  GetElem.get_attribute("href") 

As you can see from the above syntax, we are trying to get the href attribute. Now, let’s go through a working example of fetching values using the getAttribute() method now that we’ve learned the basic syntax for utilizing it.

  1. We will go to the dummy site first.
  2. On the Homepage Front-End, we will get a link’s href attribute.
  3. We will also get an image’s src attribute.

Now, let’s look at the code for this use case.

# python from selenium import webdriver  chromeDriver = webdriver.Chrome()  chromeDriver.get("https://www.inventicosolutions.com/")  getElemByLink = chromeDriver.find_element_by_link_text("About Us")  print(getElemByLink.get_attribute('href'))  getElemByClass = chromeDriver.find_element_by_xpath("/html/body/main/div/div[1]/section[1]/div/div/div/div[7]/div/img")  print(getElemByClass.get_attribute('src')) 

As we can see from the above example, we can get any attribute from an HTML tag using the getAttribute() method. This method can help us in web scraping to get specific data from a website, such as links and images.

Rana is a computer science graduate passionate about helping people to build and diagnose scalable web application problems and problems developers face across the full-stack.

Related Article — Python Selenium

Источник

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