Automating Dropdown Selection with Python using Selenium

I am currently attempting to interact with a dropdown box on a webpage. The code snippet related to the dropdown is as follows:

<span class="sui-dropdown" tabindex="0" style="width: 150px;">
<select class="dropdown-soberanos-plazo" style="display: none;">
<option value="CI">CI</option><option value="24hs">24hs</option>
<option value="48hs">48hs</option>
</select>
<span class="sui-input sui-unselectable" unselectable="on">48hs</span>
<span class="sui-caret-container sui-unselectable" unselectable="on">
<span class="sui-caret sui-unselectable" unselectable="on">
</span></span></span>

I have attempted to use the following code to select the dropdown, but unfortunately, I have been unsuccessful in doing so.

from selenium.webdriver.support.select import Select

driver.find_elements(By.XPATH,'//*[@id="soberanos"]/div/div[3]/span')
Out[176]: [<selenium.webdriver.remote.webelement.WebElement (session="f181c2e9094dce7159f3b24212735c16", element="8846fda9-7cbe-4b20-ae8c-6b6071f7a18f")>]

Select(driver.find_elements(By.XPATH,'//*[@id="soberanos"]/div/div[3]'))
Traceback (most recent call last):

  File "C:\Users\XXXXXXX\AppData\Local\Temp\ipykernel_22996\2906900798.py", line 1, in <cell line: 1>
    Select(driver.find_elements(By.XPATH,'//*[@id="soberanos"]/div/div[3]'))

  File "C:\Users\XXXXXX\Desktop\Selenium\lib\site-packages\selenium\webdriver\support\select.py", line 36, in __init__
    if webelement.tag_name.lower() != "select":

AttributeError: 'list' object has no attribute 'tag_name'

Furthermore,

 from selenium.webdriver.support.ui import Select

but this also did not yield successful results.

Despite trying different XPATH variations, the outcome remained the same.

Select(driver.find_elements(By.XPATH,'//*[@id="soberanos"]/div/div[3]/span/select'))
Traceback (most recent call last):

  File "C:\Users\ltaboada\AppData\Local\Temp\ipykernel_22996\1364519513.py", line 1, in <cell line: 1>
    Select(driver.find_elements(By.XPATH,'//*[@id="soberanos"]/div/div[3]/span/select'))

  File "C:\Users\ltaboada\Desktop\Selenium\lib\site-packages\selenium\webdriver\support\select.py", line 36, in __init__
    if webelement.tag_name.lower() != "select":

AttributeError: 'list' object has no attribute 'tag_name'

So... any suggestions or advice would be greatly appreciated!

Thank you in advance! View Dropdown Image

Answer №1

Based on the code and HTML you provided, here is a potential solution to your problem:

When using driver.find_elements, it will return a list of WebElements.

Make sure to use driver.find_element instead; pay attention to the absence of an "s" in find_element.

Therefore, your line of code would look something like this:

Select(driver.find_element(By.XPATH,'//*[@id="soberanos"]/div/div[3]'))

If this solution does not work for you, feel free to let us know.

Answer №2

Appreciate it! Success at last! Opted for a different XPATH this time

dropbox_menu_principal=wait.until(EC.element_to_be_clickable((By.XPATH,'//*[@id="topNav"]/div/div[1]/button/i')))
dropbox_menu_principal.click()

And for the internal buttons, I went with Link_Text Option.

    if(type(menues)==str):
    menu=wait.until(EC.element_to_be_clickable((By.LINK_TEXT,menues)))
    menu.click()

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

Analyze a text document containing columns arranged neatly using white spaces

One of the challenges I'm facing is parsing a text file with entries aligned in columns using multiple white spaces. Here's how the text appears: Blah blah, blah bao 123456 hello, hello, hello miao 299292929 ...

Comparing the value of a node in an XML file with a string using Python

Struggling with comparing a node from an XML file to a user-entered string in a Python script. It seems like there might be a type mismatch because the value from the XML is in unicode format. Can anyone provide a solution on how to successfully compare th ...

Is there a way to incorporate color into a particular string using python curses library?

For instance, let's say I have the string "Color chosen is blue". How can I make only the word "blue" appear in blue color? This is the code snippet that I am currently using to try and accomplish this: import curses curses.start_color() curses.ini ...

The Python BeautifulSoup module throws an AttributeError

I am attempting to extract image URLs using Beautiful Soup in Python from HTML content. This is my HTML Content: <div id="photos" class="tab rel-photos multiple-photos"> <span id="watch-this" class="classifie ...

What steps can be taken to prevent the memory leakage caused by the combination of NumPy and MKL in just

After running the following simple four-line code, I noticed a memory leak in my Python 2.6.6 / NumPy 1.7.0 / MKL 10.3.6 environment: import numpy as np t = np.random.rand(10,10) while True: t = t / np.trace(t) Each operation in the loop caused the us ...

What causes addition assignment to be noticeably slower than regular assignment?

I am relatively new to optimizing Python code for efficiency. In order to learn more, I conducted a few tests such as the following: Test Case 1: num = 0 num = 2*2 # time: 13.8 ns ± 0.158 ns per loop Test Case 2: num = 0 num += 2*2 # time: 23.8 ns ± 0. ...

Python difficulties in extracting search result links

I need assistance in extracting the search result links from a specific website. Despite using Beautiful Soup with attributes 'a' and 'href', I am unable to retrieve the links to each of the approximately 100 search results on the site ...

Encountering a cucumber error while executing my cucumber test suite

Recently started working with ROR and currently using Ruby 1.9.2p290, rvm 1.10.2, chromedriver version=18.0.995.0. Upon running the cucumber test using the following command: bundle exec cucumber features/mytest.feature An error message was displayed as ...

Error encountered in snappy/snappymodule.cc at line 31: fatal error C1083 - Unable to access the required include file 'snappy-c.h' as it does not exist in the specified directory

I am having trouble installing the python-snappy module. I successfully installed the snappy module first, but I am encountering the following error when trying to install python-snappy. (new-env) C:\Automation\test-automation\connect>pi ...

Using the glob function to parse through several CSV files can sometimes lead to an unexpected order

I am facing a challenge where I need to read multiple CSV files in the correct sequential order. The files are named with numbers like "file_0.csv", "file_1.csv", "file_2.csv", and so on, created in that specific order. However, when my code runs, the fil ...

Determine whether multiple columns in a data frame have identical values

Working on a clinical bioinformatic tool, I'm dealing with an input data frame that follows this structure: df = pd.DataFrame({'store': ['Blank_A09', 'Control_4p','13_MEG3','04_GRB10','02_PLAGL1&a ...

Executing a function on a Pandas dataframe

I am new to working with pandas dataframes, and I am looking to apply a specific function to each column. The goal is to calculate the ratio of each element in a column to the maximum value in that column. While trying to figure this out, I came across a ...

How to manage auto suggestions in the "origin" and "destination" fields for the webpage "https://www.goibibo.com/" using Selenium

How can I handle auto suggestions in the "from" and "destination" boxes on the website "https://www.goibibo.com/" using Selenium? Please assist. I have tried using the basic method but I am unable to locate the XPath of the auto suggestion drop down. I a ...

Unable to get WebdriverWait to function properly. Is there a different solution available for Python Selenium?

I took on the challenge of building scrapers for this specific website. With a total of 39 pages to scrape, I decided to split them into four groups: 1-10, 11-20, 21-30, and 31-39. Below is the snippet of code I used to access those pages: driver = webdri ...

Can a pyforms webpage accommodate the integration of a local webpage?

Looking to create a user-friendly interface for my Python application directly in the browser. One benefit of choosing Pyforms Web is its minimal requirement for HTML/CSS/JS knowledge. I am interested in incorporating an interactive Plotly dash app as a l ...

Converting a dictionary with Arabic characters to JSON utilizing the json.dumps function

I am working with a dictionary that contains Arabic words such as data = [{'name': 'آدَم'}, {'name': 'آزَر'}] print(json.dumps(data), file=open('data.json', 'a', encoding="utf-8")) When ...

No output file is created when writing to 'a', yet there are no errors reported

The objective: Accept an argument in argparse. Check if that argument is true. If true, create a file with the specified name after that argument. For example, in the command line: $ python printfile.py --out_arg fileOutput.txt This would result in ...

Issue with the @JSONString annotation causing an Illegal Argument Exception in the code generated by Cloud Endpoints

Working on a Google Cloud Endpoint web service, the authentication finally worked, but facing issues with the generated code. The ProtoRPC message is constructed with Integer fields for object id, client_id, and high_water_mark. class NoteMessage(message ...

How can I effectively transfer the output of a failed job from a gearman worker?

#!/usr/bin/env python import sys import json import gearman from fabric import * from fabric.api import * from gearman import GearmanWorker # # Executing the SSH task # def execute_job(worker, job): data = json.loads(job.data) env.host_string = d ...

Learn how to extract nested dictionaries from Json using Python (excluding dictionaries within lists)

My task involves dealing with complex JSON data structures within dictionaries: "data": { "assetID": "VMSA0000000000310652", "lastModified": "2017-06-02T19:36:36.535-04:00", "locale": { "MetadataAlbum": ...