FinestRyeBread
FinestRyeBread

Reputation: 142

Reordering options Selenium Python

Python 3.9 and Selenium 4.0.0

HTML code:

<select id="selectedDisplayColumns" name="selectedDisplayColumns" multiple="multiple" size="8">
     <option value="first_name">First Name</option>
     <option value="last_name">Last Name</option>
     <option value="phone">Phone</option>
     <option value="email">Email</option>
     <option value="city">City</option>
     <option value="state">State</option>
</select>

Whenever I run a report these options might get jumbled up so first_name could be the 4th option instead of the 1st but sometimes it could be the 1st option.

So I'm trying to basically trying to get selenium to reorder it to where it's always gonna have first name first (there's a reorder button w/ the xpath of //*[@id="configureDisplayColumnsContainer"]/fieldset/div[2]/p/input[4] and //*[@id="configureDisplayColumnsContainer"]/fieldset/div[2]/p/input[5] which is move up and move down respectively. I have to first select the option then either click move up or down to change the order.

Here is my current code:

from selenium.webdriver.support.ui import Select

#  xpath for the option menu
menu = Select(driver.find_element(By.Xpath, '//*[@id="selectedDisplayColumns"]')
selector = Select(menu)

for index in range(1, len(menu)-1):
     print(menu[index])

Upvotes: 0

Views: 123

Answers (1)

Luke Hamilton
Luke Hamilton

Reputation: 737

I would recommend using the .getAttribute feature to extract the name of the attribute. You will need to tweak this for the exact layout of the page you're scraping, but I provided a quick example that demonstrates the this feature:

element = driver.find_element_by_xpath("[@id='configureDisplayColumnsContainer']/fieldset/div[2]/p/input[0]")
attribute = element.get_attribute("value")
print(attribute)

This should print out whatever the first attribute under specific xpath is. In your code example, it should print "first_name". From there, it is just a matter of coming up with an organizational system that best fits your scraping needs.

Upvotes: 1

Related Questions