Selenium webdriver table python

Обработка html таблиц с Python и Selenium

Обработка html таблиц с Python и Selenium

Здравствуйте! В сегодняшней статье мы рассмотрим как распарсить HTML таблицу при помощи Python и Selenium webdriver. И прежде всего создадим html файл с примером таблицы.

A basic HTML table

Язык Рейтинг
Python 10
JavaScript 6

Если все сделано правильно, то в браузере должна появиться таблица.

Далее скачиваем selenium web driver для Firefox. По адресу https://github.com/mozilla/geckodriver/releases/. Называется он geckodriver. Необходимо скачать архив и распаковать его.

# Импортируем модули драйвера
import sys
from selenium import webdriver
from selenium.webdriver.common.by import By
import time

# В экземпляре класса передаем путь к exe файлу вебдрайвера

# ссылка на html таблицу,
# впереди обязательно прописываем file:///
link2 = «file:///C:/Users/УЗИ/Desktop/Таблица.html»

try:
# открываем ссылку в браузере
driver.get(link2)

# находим количество строк в таблице
rows = len(driver.find_elements(by=By.XPATH, value = ‘/html/body/table/tbody/tr’))
# подсчет количества столбцов
cols = len(driver.find_elements(by=By.XPATH, value = ‘/html/body/table/tbody/tr[1]/td’))

# итерация по строкам и столбцам таблицы
for r in range(2, rows+1):
for c in range(1, cols+1):
value = driver.find_element(by=By.XPATH, value = ‘/html/body/table/tbody/tr[‘+str(r)+’]/td[‘+str(c)+’]’).text
print(value, end = ‘ \n’)
finally:
time.sleep(30)
# обязательно прописываем выход из вебдрайвера
driver.quit()

В нашем примере используются локаторы типа /html/body/table/tbody/tr. Для его получения, необходимо сперва зайти в инструменты разработчика, выбрать элемент из ячейки таблицы и правой кнопкой мыши скопировать XPATH.

По ним вебдрайвер находит искомые элементы. Метод find_elements находит все элементы с данным локатором и возвращает список. Далее при помощи метода len вычисляется длина списка.

Для парсинга таблицы, вычисленные значения , передаются в цикл for, где они подставляются в локатор следующим образом tr[‘+str(r)+’]/td[‘+str(c)+’]. Методом text получаем текст содержащийся по данной ячейке таблицы.

Таким образом, последовательно, можно пройтись по достаточно крупной таблице с какого-либо сайта.

Создано 22.11.2022 12:41:13

  • Михаил Русаков
  • Копирование материалов разрешается только с указанием автора (Михаил Русаков) и индексируемой прямой ссылкой на сайт (http://myrusakov.ru)!

    Добавляйтесь ко мне в друзья ВКонтакте: http://vk.com/myrusakov.
    Если Вы хотите дать оценку мне и моей работе, то напишите её в моей группе: http://vk.com/rusakovmy.

    Если Вы не хотите пропустить новые материалы на сайте,
    то Вы можете подписаться на обновления: Подписаться на обновления

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

    Порекомендуйте эту статью друзьям:

    Если Вам понравился сайт, то разместите ссылку на него (у себя на сайте, на форуме, в контакте):

    1. Кнопка:
      Она выглядит вот так:
    2. Текстовая ссылка:
      Она выглядит вот так: Как создать свой сайт
    3. BB-код ссылки для форумов (например, можете поставить её в подписи):

    Комментарии ( 0 ):

    Для добавления комментариев надо войти в систему.
    Если Вы ещё не зарегистрированы на сайте, то сначала зарегистрируйтесь.

    Copyright © 2010-2023 Русаков Михаил Юрьевич. Все права защищены.

    Источник

    Dynamic Web Table Handling in Selenium

    Join

    Web tables or data tables are often used in scenarios where you need to display the information in a tabular format. The data being displayed can either be static or dynamic in nature. You’d often see such examples in e-commerce portals, where product specifications are displayed in a web table. With its wide use, you’d often come across scenarios where you’ll need to handle them in your Selenium test automation scripts.

    In this Selenium WebDriver tutorial, I’ll take a look at how to handle a web table in Selenium along with a few useful operations that can be performed on web tables. By the end of this tutorial, you’ll gain a thorough understanding of web tables in Selenium test automation along with methodologies used to access content in the web table. To know more about What is Selenium, you can refer to our detailed page on the topic.

    Below are the sub-topics covered as a part of this Selenium WebDriver tutorial:

    TABLE OF CONTENT

    What is a Web Table in Selenium?

    Web table in Selenium is a WebElement just like any other popular WebElements like text boxes, radio buttons, checkboxes, drop-down menus, etc. Web table and its contents can be accessed by using the WebElement functions along with Selenium locators to identify the element (row/column) on which the operation needs to be performed.

    A table consists of rows and columns. The table created for a web page is called a web table. Below are some of the important tags associated with a web table:

    • – Defines an HTML table
    • – Contains header information in a table
    • – Defines a row in a table
    • – Defines a column in a table

    Types of Web Tables in Selenium

    There are two broad categories of tables namely:

    Static Web Table

    As the name indicates, the information in the table is static in nature.

    Dynamic Web Table

    The information displayed in the table is dynamic. E.g. Detailed Product information on e-commerce websites, sales reports, etc.

    For the demonstration to handle the table in Selenium, we make use of a table that is available in the w3school HTML table page. Though there are fewer cross browser testing issues when using tables, some of the old browser versions of Internet Explorer, Chrome, and other web browsers do no support HTML Table APIs.

    Now that we’ve covered the basics, next in this Selenium WebDriver tutorial, I’ll take a look at some of the frequently used operations to handle tables in Selenium that would help in your Selenium test automation efforts.

    This certification is for anyone who wants to stay ahead among professionals who are growing their career in Selenium automation testing.

    Here’s a short glimpse of the Selenium 101 certification from LambdaTest:

    Handling Web Tables in Selenium

    I’ll use the local Selenium WebDriver for performing browser actions to handle table in Selenium, present on w3schools html table page. The HTML code for the web table used for demonstration is available in the tryit adapter page.

    Handling Web Tables

    The Selenium WebDriver for popular browsers can be downloaded from the locations mentioned below:

    Browser Download location
    Opera https://github.com/operasoftware/operachromiumdriver/releases
    Firefox https://github.com/mozilla/geckodriver/releases
    Chrome http://chromedriver.chromium.org/downloads
    Internet Explorer https://github.com/SeleniumHQ/selenium/wiki/InternetExplorerDriver
    Microsoft Edge https://blogs.windows.com/msedgedev/2015/07/23/bringing-automated-testing-to-microsoft-edge-through-webdriver/

    I’ll use the Python unittest framework to handle tables in Selenium WebDriver. The core logic for accessing elements in web tables still remains the same even if you are using other programming languages for Selenium test automation.

    Note – Implementation in the setUp() and teardown() remains the same for all the scenarios. We would not repeat that section in every example being shown in the blog.

    Handling Number Of Rows & Columns In Web Table

    The tag in the table indicates the rows in the table and that tag is used to get information about the number of rows in it. Number of columns of the web table in Selenium are calculated using XPath (//*[@id=’customers’]/tbody/tr[2]/td). XPath of the rows and columns are obtained using the inspect tool in the browser to handle tables in Selenium for automated browser testing.

    automated browser testing

    Source: W3School

    Though the header in a web table does not the , the tag could still be used in the current example to calculate the number of columns. The XPath for computing the number of columns using tag is //*[@id=’customers’]/tbody/tr/th

    A WebDriverWait of 30 seconds is added to ensure that the loading of the Web Table (CLASS_NAME = w3-example) is complete before any operations are performed to handle the table in Selenium.

    Get number of rows for a web table in Selenium

    Источник

    Читайте также:  Can create file php
    Оцените статью