Information about web elements
There are a number of details you can query about a specific element.
Is Displayed
This method is used to check if the connected Element is displayed on a webpage. Returns a Boolean value, True if the connected element is displayed in the current browsing context else returns false.
This functionality is mentioned in, but not defined by the w3c specification due to the impossibility of covering all potential conditions. As such, Selenium cannot expect drivers to implement this functionality directly, and now relies on executing a large JavaScript function directly. This function makes many approximations about an element’s nature and relationship in the tree to return a value.
Coding Help
Note: This section could use some updated code examples
for element displayedness
Is Enabled
This method is used to check if the connected Element is enabled or disabled on a webpage. Returns a boolean value, True if the connected element is enabled in the current browsing context else returns false.
Is Selected
This method determines if the referenced Element is Selected or not. This method is widely used on Check boxes, radio buttons, input elements, and option elements.
Returns a boolean value, True if referenced element is selected in the current browsing context else returns false.
Tag Name
It is used to fetch the TagName of the referenced Element which has the focus in the current browsing context.
Size and Position
It is used to fetch the dimensions and coordinates of the referenced element.
The fetched data body contain the following details:
- X-axis position from the top-left corner of the element
- y-axis position from the top-left corner of the element
- Height of the element
- Width of the element
Get CSS Value
Retrieves the value of specified computed style property of an element in the current browsing context.
Text Content
Retrieves the rendered text of the specified element.
Fetching Attributes or Properties
Fetches the run time value associated with a DOM attribute. It returns the data associated with the DOM attribute or property of the element.
Selenium Level Sponsors
Support the Selenium Project
Want to support the Selenium project? Learn more or view the full list of sponsors.
Python Selenium — get href value
I am trying to copy the href value from a website, and the html code looks like this:
I’ve tried driver.find_elements_by_css_selector(«.sc-eYdvao.kvdWiq»).get_attribute(«href») but it returned ‘list’ object has no attribute ‘get_attribute’ . Using driver.find_element_by_css_selector(«.sc-eYdvao.kvdWiq»).get_attribute(«href») returned None . But i cant use xpath because the website has like 20+ href which i need to copy all. Using xpath would only copy one.
If it helps, all the 20+ href are categorised under the same class which is sc-eYdvao kvdWiq .
Ultimately i would want to copy all the 20+ href and export them out to a csv file.
Работа с ссылками в Selenium
Ссылки являются фундаментальными элементами веб-страниц. По сути, это гиперссылки, которые делают возможным существование всемирной интернет сети. Ниже приведен пример ссылки, а также источник HTML.
Запуск браузера
Тестирование веб-сайтов начинается с браузера.
Используйте webdriver.Chrome или webdriver.Ie для тестирования в Chrome и IE соответственно. Для новичков рекомендуется закрыть окно браузера в конце тестового примера.
Найти ссылку по тексту
Поиск по тексту — это, пожалуй, самый прямой способ найти ссылку в Selenium, поскольку это то, что мы видим на странице.
Найти ссылку по ID
Кроме того, если вы тестируете веб-сайт с несколькими языками, использование идентификаторов является, пожалуй, единственно возможным вариантом. Если вы не хотите писать тестовые скрипты, как показано ниже:
Найти ссылку по частичному тексту
Найти ссылку при помощи XPath
Пример ниже — поиск ссылки с текстом «Recommend Selenium» под тегом абзаца <p>.
Можно сказать, что приведенный выше пример (найти по тексту ссылки) проще и интуитивно понятнее. Но давайте рассмотрим другой пример:
На этой странице есть две ссылки «Click here». Если в тестовом случае вам нужно щелкнуть вторую ссылку «Click here», простой find_element_by_link_text («Click here«) не будет работать (так как он нажимает первый). Вот способ выполнения XPath:
Клик на N-ую ссылку с похожим текстом
Это не редкость, что существует более одной ссылки с точно таким же текстом. По умолчанию Selenium выберет первый. Что, если вы выберете второй или N-ый? На приведенной ниже веб-странице есть три ссылки «Show Answer».
Чтобы выбрать вторую ссылку:
find_elements_xxx возвращает список (также называемый массивом) веб-элементов, соответствующих критериям в порядке появления. Selenium (Python) использует индексирование на основе нуля, то есть первое из них равно 0.
Клик на N-ую ссылку по CSS критериям
Вы также можете использовать CSS выражения для поиска веб-элемента.
Working With Links using Selenium WebDriver
Links in HTML are nothing but hyperlinks. When we click on a link, we are navigated to another page or document.
HTML links are defined with anchor (<a>) tags.
Example:
Here in above code, “href“ is an attribute which specifies the address of another HTML page and “Selenium Tutorial” is the link text associated with it. (i.e. the visible part on the page).
Identifiers in Selenium WebDriver to Interact with Links:
Selenium WebDriver provides two different identifiers to interact with links.
- linktext()
- partialLinktext()
linktext() identifier matches exact text associated with the link web element. So, to click on above-mentioned link code will be:
partialLinktext() identifier matches partial text associated with the link web element. It can be considered as a contains method. So, to click on above-mentioned link code will be:
Actions performed on Links:
We can perform different actions on a link like click(), getText(), moverHover().
The click() method is to click on the mentioned link, this will navigate you to another webpage in the same window or in another window.
The getText() method is to fetch the text from a link. Below code will return “Selenium Tutorial”.
The mouseHover() operation we will learn in detail in later classes.
Getting Attribute from an HTML Tag:
One of the important scenario while working with links is to get the URL from the link. getAttribute(“String”) method is used to get the url from the link. See the below example, for above HTML link the code will return “http://qatechub.com/selenium”.
Let us try some interview based scenarios:
Scenario 1: Counting numbers of link on a web page say Flipkart
- Open any browser say “Chrome”
- Navigate to Flipkart website. (http://www.flipkart.com)
- Write a code to get the number of links on this page.
To get the number of links on a page, we will first get all the links using a method called findElements(By.tagName(“a”)). This method will return a list of all the WebElements in a list. Call size() method to get the count of the number of WebElements i.e. number of links.
To Execute the code let us create a main method:
In above code, getNumberOfLinks() method is used to get the number of links from a page.
Scenario 2: Printing the text associated with all the links and their URL on a page say Flipkart.
- Open any browser say “Chrome.”
- Navigate to Flipkart site (http://www.flipkart.com)
- Write a code to get the number of links on this page.
- Write a code to get the text associated with each link and its URL.
This scenario is an extension of the above scenario. Here, after finding the number of links. We will iterate over each link and fetch its text using a method called getText() and fetch its URL by a method called getAttribute(“href”).
Refer below code for the same:
Enhanced for loop is used to iterate over each link, fetching its text and associated url.
This is all in this tutorial, I hope you enjoyed the different scenario’s possible with links using Selenium WebDriver.