RUVIDEO
Поделитесь видео 🙏

How To: Find_Elements() In Selenium (3 Min) Using Python, PyTest, PyCharm

In this tutorial, you'll learn how to use find_elements method in Selenium using Pytest, Python & PyCharm.

Facebook: https://www.facebook.com/GokceDBsql

Video Transcript:

Hi guys, this is Abhi from Gokcedb. In this video, you're going to learn how to use the find underscore elements method in Selenium using the PI test. Let's start by looking at the test scenario.

I want to go to amazon.com and search for the keyword sunglasses. From the first search result page, I want to grab all the prices and check whether the average price is less than 50 dollars or not. Now let's look at the test directory structure inside amazon underscore tests folder.

I have a conf test.py file that contains the driver fixture function. This function is responsible for initializing the Chrome web driver. Next, I have the test underscore amazon underscore search1.py file containing a test function.

On line 8, I'm using the get method to go to amazon.com. In the next line, I'm searching for the keyword sunglasses. Line 10, I'm clicking on the search submit button.

Net I'm using the list comprehension syntax to grab all the prices from the first search results page and storing it in list underscore prices. On line 15, I'm calculating the average by dividing the sum of list underscore prices by its length. Finally, on line 19, I'm asserting whether the average price is less than 50 dollars or not.

Next, let's look at the page underscore object directory structure. I have a locators.py file under locators which contains all the x paths and ids. Whereas in pages.py file I have defined all the helper methods used to fund elements on the web page.

Next to execute the test file, right-click on it and select run PI test. Looks like the average price on the first search average price on the first results page was 38.71, which is less than 50 dollars and that's the reason why our test passed.

Now, let's look at how to find the Xpath locator that we used to grab all the product prices. Start by clicking on the button with three dots and select developer tools from the more tools drop-down. Now click on the inspect button and hover over the price. Click on it to get the corresponding HTML code and grab the span class from there.

Now you can use the get underscore attribute method to get the inner text from this pen class. Finally, to export the test results in an HTML file, click on the export test results button. There you have it.

Make sure you like, subscribe, and turn on the notification bell. Until next time.

Connect MySQL In Python: https://www.youtube.com/watch?v=0qBctY82et0
Run Selenium PyTests In Parallel: https://www.youtube.com/watch?v=cQE6ABZ9I14

from tests.page_object.pages.pages import AmazonHomePage, AmazonSearchPage
def test_average_price_in_search_result(driver):
amazon_home_page = AmazonHomePage(driver)
amazon_search_page = AmazonSearchPage(driver)
driver.get(amazon_home_page.get_url())
amazon_home_page.get_search_text_box_by_id().send_keys("sunglasses")
amazon_home_page.get_search_submit_button_by_id().click()
list_prices = [float(_.get_attribute("innerHTML").replace('$', ''))
for _ in amazon_search_page.get_all_product_prices_by_xpath()]
average = sum(list_prices)/len(list_prices)
print("Average price of sunglasses on the first search result page:", round(average, 2))
assert average [REMOVED] 50
import pytest
from selenium import webdriver
import os
@pytest.fixture()
def driver():
root_dir = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
driver = webdriver.Chrome(executable_path=root_dir + '/resources/chromedriver')
# Time in seconds driver should wait when searching for an element if it is not
# immediately present
driver.implicitly_wait(2)
yield driver
driver.quit()
class AmazonHomePageLocator:
url = "https://www.amazon.com/"
search_text_box_id = "twotabsearchtextbox"
search_submit_button_id = "nav-search-submit-button"
class AmazonSearchPageLocator:
amazons_choice_label_xpath = "//*[contains(@id,'amazons-choice-label')]"
all_product_prices_xpath = './/span[@class="a-offscreen"]'
from tests.page_object.locators.locators import AmazonHomePageLocator, AmazonSearchPageLocator
from selenium.webdriver.common.by import By
class AmazonHomePage:
def __init__(self, driver):
self.driver = driver
@staticmethod
def get_url():
return AmazonHomePageLocator.url
def get_search_text_box_by_id(self):
return self.driver.find_element(By.ID, AmazonHomePageLocator.search_text_box_id)
def get_search_submit_button_by_id(self):
return self.driver.find_element(By.ID, AmazonHomePageLocator.search_submit_button_id)
class AmazonSearchPage:
def __init__(self, driver):
self.driver = driver
def get_all_product_prices_by_xpath(self):
return self.driver.find_elements(By.XPATH,

Что делает видео по-настоящему запоминающимся? Наверное, та самая атмосфера, которая заставляет забыть о времени. Когда вы заходите на RUVIDEO, чтобы посмотреть онлайн «How To: Find_Elements() In Selenium (3 Min) Using Python, PyTest, PyCharm», вы рассчитываете на нечто большее, чем просто загрузку плеера. И мы это понимаем. Контент такого уровня заслуживает того, чтобы его смотрели в HD 1080, без дрожания картинки и бесконечного буферизации.

Честно говоря, Rutube сегодня — это кладезь уникальных находок, которые часто теряются в общем шуме. Мы же вытаскиваем на поверхность самое интересное. Будь то динамичный экшн, глубокий разбор темы от любимого автора или просто уютное видео для настроения — всё это доступно здесь бесплатно и без лишних формальностей. Никаких «заполните анкету, чтобы продолжить». Только вы, ваш экран и качественный поток.

Если вас зацепило это видео, не забудьте взглянуть на похожие материалы в блоке справа. Мы откалибровали наши алгоритмы так, чтобы они подбирали контент не просто «по тегам», а по настроению и смыслу. Ведь в конечном итоге, онлайн-кинотеатр — это не склад файлов, а место, где каждый вечер можно найти свою историю. Приятного вам отдыха на RUVIDEO!

Видео взято из открытых источников Rutube. Если вы правообладатель, обратитесь к первоисточнику.