Selenium get all attributes python

Selenium webdriver: Как мне найти ВСЕ атрибуты элемента?

В модуле Selenium Python, когда у меня есть объект WebElement, я могу получить значение любого из его атрибутов с помощью get_attribute() :

foo = elem.get_attribute('href') 

Если атрибут с именем ‘href’ не существует, возвращается None. Мой вопрос: как я могу получить список всех атрибутов, которые имеет элемент? Кажется, что не существует методов get_attributes() или get_attribute_names() .

3 ответа

Невозможно использовать API-интерфейс selenium webdriver, но вы можете выполнить код javascript для получения всех атрибутов:

driver.execute_script('var items = <>; for (index = 0; index < arguments[0].attributes.length; ++index) < items[arguments[0].attributes[index].name] = arguments[0].attributes[index].value >; return items;', element) 
>>> from selenium import webdriver >>> from pprint import pprint >>> driver = webdriver.Firefox() >>> driver.get('https://stackoverflow.com') >>> >>> element = driver.find_element_by_xpath('//div[@class="network-items"]/a') >>> attrs = driver.execute_script('var items = <>; for (index = 0; index < arguments[0].attributes.length; ++index) < items[arguments[0].attributes[index].name] = arguments[0].attributes[index].value >; return items;', element) >>> pprint(attrs) 

Для полноты решения альтернативным решением было бы получить тег outerHTML и проанализировать атрибуты с помощью парсера HTML. Пример (с помощью BeautifulSoup ):

>>> from bs4 import BeautifulSoup >>> html = element.get_attribute('outerHTML') >>> attrs = BeautifulSoup(html, 'html.parser').a.attrs >>> pprint(attrs) 

Есть идеи, почему это не было включено в спецификацию W3C? Кажется близоруким, чтобы оставить это вне w3.org/TR/webdriver/#get-element-attribute

@raven не уверен, может, это просто не так широко используется. Гораздо чаще пользователь хотел бы получить один атрибут . хороший вопрос, хотя, спасибо.

Ниже представлен список всех атрибутов и их (иногда переведенных на строки) значений для меня, используя, по крайней мере, драйвер PhantomJS или Chrome:

elem.get_property('attributes')[0] 

Чтобы просто получить имена:

x.get_property('attributes')[0].keys() 

Вот моя попытка ответить. Я проверил его только в окне поиска на главной странице google. Я использовал @alecxe ответ выше «outerHTML» Получив html, я использовал регулярное выражение ([a-z]+-?[a-z]+_?)=’?»? для соответствия именам атрибутов. Я думаю, что регулярное выражение просто нужно будет изменить, чтобы соответствовать все большему числу случаев. Но главное имя, которое нам нужно, — «что стоит за знаком равенства».

def get_web_element_attribute_names(web_element): """Get all attribute names of a web element""" # get element html html = web_element.get_attribute("outerHTML") # find all with regex pattern = """([a-z]+-?[a-z]+_?)='?"?""" return re.findall(pattern, html) 

Проверьте его на приведенном ниже коде

import re from selenium import webdriver driver = webdriver.Firefox() google = driver.get("http://www.google.com") driver.find_element_by_link_text("English").click() search_element = driver.find_element_by_name("q") get_web_element_attribute_names(search_element) 
['class', 'id', 'maxlength', 'name', 'autocomplete', 'title', 'value', 'aria-label', 'aria-haspopup', 'role', 'aria-autocomplete', 'style', 'dir', 'spellcheck', 'type'] 

Ещё вопросы

  • 1 Как установить ориентацию видов под наложением жестов на «нет»
  • 1 Расовые условия с использованием Office.js в Excel
  • 0 Очистить класс CSS на нумерации строк таблицы
  • 1 Каково идеальное место для кэширования изображений?
  • 0 AngularJS -Контроллер не вызывается
  • 1 Отключение событий JS
  • 1 Как получить данные из базы данных в реальном времени в Firebase?
  • 0 MYSQL Query — Использование оператора Select в предложении Where
  • 0 Knockout Mapping для изображения (ссылки) в Json
  • 1 Триггер SQL Server для параметра «По умолчанию (newsequentialid ())» не работает с «00000000-0000-0000-0000-000000000000»?
  • 0 как показать сообщения проверки при отправке формы в угловых js
  • 1 Разобрать элемент XML с тем же тегом, используя Sax
  • 1 Скрепка с ActionCable
  • 1 Изменить цвет списка, если
  • 1 Приложение для Android: передача Javascript Var в переменную Native Java
  • 1 Как я могу отправить данные в определенный сокет?
  • 1 Может ли JavaScript запускать несколько функций одновременно?
  • 0 Запуск 2 xampp на том же локальном компьютере
  • 1 Счетчик времени Vue.js
  • 1 HashMap с определенным временем поиска?
  • 0 Перезаписать вывод foreach, если существует повторяющееся значение
  • 0 угловая анимация, сдвиньте вправо выдвиньте влево
  • 0 Конвертировать плоский массив PHP в многомерный массив
  • 1 Конструктор объекта указывает на исходный конструктор, а не на prototype.constructor после переопределения прототипа функции конструктора.
  • 0 Передача const char * в foo (char *)
  • 0 Определите несколько контроллеров в одном маршруте [дубликаты]
  • 1 Bing Maps v8 — встроенная канцелярская кнопка SVG не запускает правильный информационный блок
  • 0 Слияние сложных массивов
  • 0 Как расположить кнопку ввода файла с правой стороны внутри текстового поля
  • 0 PHP: как вернуть счетчик значения из рекурсивной функции?
  • 1 Событие щелчка LinkButton не срабатывает, если какое-либо действие, выполненное с клавишей ENTER, вместо нажатия кнопки
  • 1 Как извлечь все промежутки на странице, используя iMacros?
  • 1 Как реализовать обнаружение столкновения полилиний в Javascript
  • 0 Как правильно получить ресурсы с условно-инициализированными объектами в C ++?
  • 0 AngularJS просмотры нарушены после перенаправления oauth
  • 0 Цвет наложения JQuery FancyBox
  • 0 манипулирование таблицей html с использованием foreach в codeigniter
  • 1 FileLoadException не обработан
  • 1 AttributeError: у объекта ‘numpy.ndarray’ нет атрибута ‘getdraw’
  • 0 Правильный синтаксис для запуска скрипта через cron
  • 0 C / C ++: `const` позиция в списке аргументов функции
  • 0 Не отображаются средние значения для пользователей с более чем одним экземпляром
  • 1 Twitter Bot — node.js — неожиданная ошибка токена
  • 1 Как мне перенести расширение в VB.NET на C #?
  • 1 Firebaserecycleadapter, в чем разница с «обычным» recycleradapter? (Андроид)
  • 1 NeedHelp Отладка: добавление двух списков ArrayLists с использованием метода — Java
  • 1 ApiDeadlineExceededException с использованием клиента WebService в GWT WebApp
  • 1 Сложная, но эффективная фильтрация массива JavaScript
  • 0 Mysql конвертировать целое число в дату
  • 1 Копировать весь текстовый документ, включая таблицы, в другой, используя Python

Источник

selenium.webdriver.remote.webelement¶

ABC’s will allow custom types to be registered as a WebElement to pass type checks.

class selenium.webdriver.remote.webelement. WebElement ( parent, id_ ) [source] ¶

Generally, all interesting operations that interact with a document will be performed through this interface.

All method calls will do a freshness check to ensure that the element reference is still valid. This essentially determines whether the element is still attached to the DOM. If this test fails, then an StaleElementReferenceException is thrown, and all future calls to this instance will fail.

Returns the ARIA Level of the current webelement.

Returns the ARIA role of the current web element.

Clears the text if it’s a text entry element.

find_element ( by=’id’, value=None ) → selenium.webdriver.remote.webelement.WebElement [source] ¶

Find an element given a By strategy and locator.

element = element.find_element(By.ID, 'foo') 

Find elements given a By strategy and locator.

element = element.find_elements(By.CLASS_NAME, 'foo') 

Gets the given attribute or property of the element.

This method will first try to return the value of a property with the given name. If a property with that name doesn’t exist, it returns the value of the attribute with the same name. If there’s no attribute with that name, None is returned.

Values which are considered truthy, that is equals “true” or “false”, are returned as booleans. All other non- None values are returned as strings. For attributes or properties which do not exist, None is returned.

To obtain the exact value of the attribute or property, use get_dom_attribute() or get_property() methods respectively.

# Check if the "active" CSS class is applied to an element. is_active = "active" in target_element.get_attribute("class") 

Gets the given attribute of the element. Unlike get_attribute() , this method only returns attributes declared in the element’s HTML markup.

text_length = target_element.get_dom_attribute("class") 

Gets the given property of the element.

text_length = target_element.get_property("text_length") 

Internal ID used by selenium.

This is mainly for internal use. Simple use cases such as checking if 2 webelements refer to the same element, can be done using == :

if element1 == element2: print("These 2 are equal") 

Whether the element is visible to a user.

Returns whether the element is enabled.

Returns whether the element is selected.

Can be used to check if a checkbox or radio button is selected.

The location of the element in the renderable canvas.

THIS PROPERTY MAY CHANGE WITHOUT WARNING. Use this to discover where on the screen an element is so that we can click it. This method should cause the element to be scrolled into view.

Returns the top lefthand corner location on the screen, or zero coordinates if the element is not visible.

Internal reference to the WebDriver instance this element was found from.

A dictionary with the size and location of the element.

screenshot ( filename ) → bool [source] ¶

Saves a screenshot of the current element to a PNG image file. Returns False if there is any IOError, else returns True. Use full paths in your filename.

  • filename: The full path you wish to save your screenshot to. This should end with a .png extension.
element.screenshot('/Screenshots/foo.png') 

Gets the screenshot of the current element as a base64 encoded string.

img_b64 = element.screenshot_as_base64 

Gets the screenshot of the current element as a binary data.

element_png = element.screenshot_as_png 

Simulates typing into the element.

  • value — A string for typing, or setting form fields. For setting file inputs, this could be a local file path.

Use this to send simple key events or to fill out form fields:

form_textfield = driver.find_element(By.NAME, 'username') form_textfield.send_keys("admin") 

This can also be used to set file inputs.

file_input = driver.find_element(By.NAME, 'profilePic') file_input.send_keys("path/to/profilepic.gif") # Generally it's better to wrap the file path in one of the methods # in os.path to return the actual path to support cross OS testing. # file_input.send_keys(os.path.abspath("path/to/profilepic.gif")) 

Returns a shadow root of the element if there is one or an error. Only works from Chromium 96, Firefox 96, and Safari 16.4 onwards.

This element’s tagName property.

value_of_css_property ( property_name ) → str [source] ¶

The value of a CSS property.

Источник

Читайте также:  Html variable in div
Оцените статью