How can I implement an if-else statement using CSS in Python Selenium?

I am attempting to create an if else statement that checks for the existence of a specific CSS element.

If the first CSS element does not exist, it should then click on the second CSS element.

Here is my current code:

    
#IF STATEMENT
      driver.find_element_by_css_selector('.GA_Track_Action_Download-FullHD-1080p > .movieQuality').click()
 
#ELSE STATEMENT
      driver.find_element_by_css_selector('.GA_Track_Action_Download-4K-2160p > .movieQuality').click()
    

This is what I've attempted:

if is_element_exist(driver, '.GA_Track_Action_Download-FullHD-1080p > .movieQuality''):
      driver.find_element_by_css_selector('.GA_Track_Action_Download-FullHD-1080p > .movieQuality').click()

else:
      driver.find_element_by_css_selector('.GA_Track_Action_Download-4K-2160p > .movieQuality').click()

However, this solution does not seem to be working as expected.

Answer №1

attempt:
    driver.find_element(By.CSS_SELECTOR,".GA_Track_Action_Download-FullHD-1080p > .movieQuality,(OR) .GA_Track_Action_Download-4K-2160p > .movieQuality").click()
excepting:
    bypass

Have you considered using ,(OR) to verify for either option?

Answer №2

Give this a try and verify.

Select the Item from a Collection and validate if the Collection is Empty or not. If the size of the Collection is 0, the instructions in the else block will be executed.

if len([driver.find_element(By.CSS_SELECTOR,".GA_Track_Action_Download-FullHD-1080p > .movieQuality")]) > 0:
    driver.find_element(By.CSS_SELECTOR, ".GA_Track_Action_Download-FullHD-1080p > .movieQuality").click()

else:
    driver.find_element(By.CSS_SELECTOR,".GA_Track_Action_Download-4K-2160p > .movieQuality").click()

Answer №3

To replace an if-else block, consider using a try-except{} block and handle the exception to perform a click on the second element in this way:

try:
    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, ".GA_Track_Action_Download-4K-2160p > .movieQuality"))).click()
except TimeoutException:
    driver.find_element(By.CSS_SELECTOR,".GA_Track_Action_Download-4K-2160p > .movieQuality").click()

Note: Make sure to include the following imports:

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for implementing a slide up animation on a dynamic element

I have one div and a button. When the button is clicked, I am appending another div. After appending the second div, I want to add a slide-up animation to the first div and a slide-down animation to the second using jQuery. <div class="main"> & ...

A handy PHP tool designed to create CSS shorthand code efficiently

Currently, I am programming a PHP script to generate dynamic CSS styles. Each value is specified individually like so: $padding_top = 10; $padding_bottom = 10; $padding_left = 10; $padding_right = 10; My goal now is to create shorthand CSS rules where ...

Looking for details on the most recent setup of Chrome Driver?

In the past, when launching Chrome Driver, we used to set properties using the chromedriver.exe file or the command WebDriverManager.chromedriver().setup(). However, with the latest version of Chrome, it seems to be working fine without the need for the We ...

Insert PDF to completely fill the screen

Seeking advice on embedding a PDF in an HTML document with a consistent height of 100%. The challenge lies in the varying height of the PDF, and the need for the layout to adapt accordingly. ...

How to eliminate spacing between slides in a 3D Carousel Slider using Bootstrap 5

My website utilizes Bootstrap along with a carousel slider, which is functioning properly. However, I am encountering an issue when the slider transitions from right to left. It briefly displays a white space between slides, which I wish to eliminate. I wa ...

The titles and view counts of YouTube videos are not displayed

I am currently working on a project to extract and print the title and view count of each video from different YouTube channels listed in my urls. I encountered an issue where it only displayed results for one channel (https://www.youtube.com/c/TuckerBud ...

"Learn how to feed parameters from a Selenium Java test file into a Karate feature file for seamless integration

I am looking to send an argument from a Selenium Java test to a Karate GraphQL test. I attempted it this way, but unfortunately, it did not work. HashMap<String, Object> args = new HashMap<String, Object>(); args.put("argument1", "value1"); Ma ...

Click Event for Basic CSS Dropdown Menu

My goal is to develop a straightforward feature where a dropdown menu appears below a specific text field once it is clicked. $(".val").children("div").on("click", function() { alert("CLICK"); }); .container { display: inline-block; } .val { d ...

Creating a dynamic dropdown menu that displays options based on the selection made in a previous drop

Attempting to replicate this exact functionality on my own site has proven difficult. Despite success on jsfiddle, none of the browsers I've tested seem to cooperate. Any suggestions? Even when isolated as the sole element on a page, it simply refuses ...

What is causing this animation to malfunction?

Could someone assist me in hiding this div-container for a brief period of 2 seconds? If you have any alternative suggestions, feel free to share them but, please refrain from using jQuery or JavaScript. #vcontainer { height: 450px; width: 100%; ba ...

An issue has been identified where a single image is not displaying properly on Android devices, as well as IE7 and

Hey there! I recently created a Wordpress site and it seems that the Art Below logo isn't appearing in IE7, IE8, and Android for some reason. Would anyone be willing to help troubleshoot this issue? If you have fresh eyes, please take a look at the f ...

JavaScript code to generate a random color for the box shadow effect

Recently, I developed a function that generates random divs containing circles. The function randomly selects a border color for each circle, and this feature is functioning correctly. To enhance the appearance, I decided to add a box shadow to the circl ...

Using javascript to quickly change the background to a transparent color

I am in the process of designing a header for my website and I would like to make the background transparent automatically when the page loads using JavaScript. So far, I have attempted several methods but none seem to be working as desired. The CSS styles ...

Modify the color of links when hovering using CSS

I am currently utilizing VScode and attempting to modify the link color on :hover. I am also interested in adding a grow Hover Effect. Here is my code snippet: .subareas a.link { margin: 0 0 10px 10px; float: right; height: 30px; line-height: 29 ...

Error: The 'chromedriver' executable must be included in the PATH when running Python Selenium on a web server

I have been working on a python script for web scraping using selenium, and everything runs smoothly on my local laptop. However, when I try to run the same script on the web server, I keep encountering errors related to selenium which prevent successful e ...

Step-by-step guide on duplicating a div a set number of times

I am looking to replicate the entire div multiple times (e.g., on an A4 paper, top left corner, top right corner, bottom left corner, and bottom right corner). <script language="javascript" type='text/javascript'> function updateD ...

WebDriverError: Unable to access the profile. Perplexed by the issue at hand

After relying on webdriver.Firefox() for several years, I encountered an issue today when starting a new project. The code browser = webdriver.Firefox() is now returning the following error: WebDriverException: Message: Can't load the profile. Profil ...

Guide to selecting a pop-up button in Python using Selenium

I've been trying to click on a popup window, but no matter what I do, I keep getting a "TimeoutException" error. Here is the code snippet that I've been attempting to use: WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, "// ...

Present the "Read more" button aligned with v-html content

I have some HTML content that I want to display using the v-html directive. The text is quite lengthy, so I am looking to add a clickable Read more link that appears on the same line as the text. The code structure would look like this: <div v-html=&qu ...

I'm having trouble getting my modal to open, it just displays the information on my page instead

I am encountering some difficulties with my model window. I would like it to open a modal that shows a larger version of the photo and description when the thumbnail is clicked. However, I have not been able to get it to work properly. The only time it pop ...